ai-flow-dev 2.7.0 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +573 -570
  3. package/package.json +74 -74
  4. package/prompts/backend/flow-build-phase-0.md +535 -535
  5. package/prompts/backend/flow-build-phase-1.md +626 -626
  6. package/prompts/backend/flow-build-phase-10.md +340 -340
  7. package/prompts/backend/flow-build-phase-2.md +573 -573
  8. package/prompts/backend/flow-build-phase-3.md +834 -834
  9. package/prompts/backend/flow-build-phase-4.md +554 -554
  10. package/prompts/backend/flow-build-phase-5.md +703 -703
  11. package/prompts/backend/flow-build-phase-6.md +524 -524
  12. package/prompts/backend/flow-build-phase-7.md +1001 -1001
  13. package/prompts/backend/flow-build-phase-8.md +1407 -1407
  14. package/prompts/backend/flow-build-phase-9.md +477 -477
  15. package/prompts/backend/flow-build.md +137 -137
  16. package/prompts/backend/flow-check-review.md +656 -20
  17. package/prompts/backend/flow-check-test.md +526 -14
  18. package/prompts/backend/flow-check.md +717 -67
  19. package/prompts/backend/flow-commit.md +88 -119
  20. package/prompts/backend/flow-docs-sync.md +354 -354
  21. package/prompts/backend/flow-finish.md +919 -0
  22. package/prompts/backend/flow-release.md +949 -0
  23. package/prompts/backend/flow-work-feature.md +61 -61
  24. package/prompts/backend/flow-work-fix.md +46 -46
  25. package/prompts/backend/flow-work-refactor.md +48 -48
  26. package/prompts/backend/flow-work-resume.md +34 -34
  27. package/prompts/backend/flow-work.md +1098 -1286
  28. package/prompts/desktop/flow-build-phase-0.md +359 -359
  29. package/prompts/desktop/flow-build-phase-1.md +295 -295
  30. package/prompts/desktop/flow-build-phase-10.md +357 -357
  31. package/prompts/desktop/flow-build-phase-2.md +282 -282
  32. package/prompts/desktop/flow-build-phase-3.md +291 -291
  33. package/prompts/desktop/flow-build-phase-4.md +308 -308
  34. package/prompts/desktop/flow-build-phase-5.md +269 -269
  35. package/prompts/desktop/flow-build-phase-6.md +350 -350
  36. package/prompts/desktop/flow-build-phase-7.md +297 -297
  37. package/prompts/desktop/flow-build-phase-8.md +541 -541
  38. package/prompts/desktop/flow-build-phase-9.md +439 -439
  39. package/prompts/desktop/flow-build.md +156 -156
  40. package/prompts/desktop/flow-check-review.md +656 -20
  41. package/prompts/desktop/flow-check-test.md +526 -14
  42. package/prompts/desktop/flow-check.md +717 -67
  43. package/prompts/desktop/flow-commit.md +88 -119
  44. package/prompts/desktop/flow-docs-sync.md +354 -354
  45. package/prompts/desktop/flow-finish.md +919 -0
  46. package/prompts/desktop/flow-release.md +662 -0
  47. package/prompts/desktop/flow-work-feature.md +61 -61
  48. package/prompts/desktop/flow-work-fix.md +46 -46
  49. package/prompts/desktop/flow-work-refactor.md +48 -48
  50. package/prompts/desktop/flow-work-resume.md +34 -34
  51. package/prompts/desktop/flow-work.md +1202 -1390
  52. package/prompts/frontend/flow-build-phase-0.md +425 -425
  53. package/prompts/frontend/flow-build-phase-1.md +626 -626
  54. package/prompts/frontend/flow-build-phase-10.md +33 -33
  55. package/prompts/frontend/flow-build-phase-2.md +573 -573
  56. package/prompts/frontend/flow-build-phase-3.md +782 -782
  57. package/prompts/frontend/flow-build-phase-4.md +554 -554
  58. package/prompts/frontend/flow-build-phase-5.md +703 -703
  59. package/prompts/frontend/flow-build-phase-6.md +524 -524
  60. package/prompts/frontend/flow-build-phase-7.md +1001 -1001
  61. package/prompts/frontend/flow-build-phase-8.md +872 -872
  62. package/prompts/frontend/flow-build-phase-9.md +94 -94
  63. package/prompts/frontend/flow-build.md +137 -137
  64. package/prompts/frontend/flow-check-review.md +656 -20
  65. package/prompts/frontend/flow-check-test.md +526 -14
  66. package/prompts/frontend/flow-check.md +717 -67
  67. package/prompts/frontend/flow-commit.md +88 -119
  68. package/prompts/frontend/flow-docs-sync.md +550 -550
  69. package/prompts/frontend/flow-finish.md +919 -0
  70. package/prompts/frontend/flow-release.md +519 -0
  71. package/prompts/frontend/flow-work-api.md +1547 -0
  72. package/prompts/frontend/flow-work-feature.md +61 -61
  73. package/prompts/frontend/flow-work-fix.md +38 -38
  74. package/prompts/frontend/flow-work-refactor.md +48 -48
  75. package/prompts/frontend/flow-work-resume.md +34 -34
  76. package/prompts/frontend/flow-work.md +1595 -1320
  77. package/prompts/mobile/flow-build-phase-0.md +425 -425
  78. package/prompts/mobile/flow-build-phase-1.md +626 -626
  79. package/prompts/mobile/flow-build-phase-10.md +32 -32
  80. package/prompts/mobile/flow-build-phase-2.md +573 -573
  81. package/prompts/mobile/flow-build-phase-3.md +782 -782
  82. package/prompts/mobile/flow-build-phase-4.md +554 -554
  83. package/prompts/mobile/flow-build-phase-5.md +703 -703
  84. package/prompts/mobile/flow-build-phase-6.md +524 -524
  85. package/prompts/mobile/flow-build-phase-7.md +1001 -1001
  86. package/prompts/mobile/flow-build-phase-8.md +888 -888
  87. package/prompts/mobile/flow-build-phase-9.md +90 -90
  88. package/prompts/mobile/flow-build.md +135 -135
  89. package/prompts/mobile/flow-check-review.md +656 -20
  90. package/prompts/mobile/flow-check-test.md +526 -14
  91. package/prompts/mobile/flow-check.md +717 -67
  92. package/prompts/mobile/flow-commit.md +88 -119
  93. package/prompts/mobile/flow-docs-sync.md +620 -620
  94. package/prompts/mobile/flow-finish.md +919 -0
  95. package/prompts/mobile/flow-release.md +751 -0
  96. package/prompts/mobile/flow-work-api.md +1500 -0
  97. package/prompts/mobile/flow-work-feature.md +61 -61
  98. package/prompts/mobile/flow-work-fix.md +46 -46
  99. package/prompts/mobile/flow-work-refactor.md +48 -48
  100. package/prompts/mobile/flow-work-resume.md +34 -34
  101. package/prompts/mobile/flow-work.md +1605 -1329
  102. package/prompts/shared/mermaid-guidelines.md +102 -102
  103. package/prompts/shared/scope-levels.md +114 -114
  104. package/prompts/shared/smart-skip-preflight.md +214 -214
  105. package/prompts/shared/story-points.md +55 -55
  106. package/prompts/shared/task-format.md +74 -74
  107. package/prompts/shared/task-summary-template.md +277 -277
  108. package/templates/AGENT.template.md +443 -443
  109. package/templates/backend/.clauderules.template +112 -112
  110. package/templates/backend/.cursorrules.template +102 -102
  111. package/templates/backend/README.template.md +2 -2
  112. package/templates/backend/ai-instructions.template.md +2 -2
  113. package/templates/backend/copilot-instructions.template.md +2 -2
  114. package/templates/backend/docs/api.template.md +320 -320
  115. package/templates/backend/docs/business-flows.template.md +97 -97
  116. package/templates/backend/docs/code-standards.template.md +2 -2
  117. package/templates/backend/docs/contributing.template.md +3 -3
  118. package/templates/backend/docs/data-model.template.md +520 -520
  119. package/templates/backend/docs/testing.template.md +2 -2
  120. package/templates/backend/project-brief.template.md +2 -2
  121. package/templates/backend/specs/configuration.template.md +2 -2
  122. package/templates/backend/specs/security.template.md +2 -2
  123. package/templates/desktop/.clauderules.template +112 -112
  124. package/templates/desktop/.cursorrules.template +102 -102
  125. package/templates/desktop/README.template.md +170 -170
  126. package/templates/desktop/ai-instructions.template.md +366 -366
  127. package/templates/desktop/copilot-instructions.template.md +140 -140
  128. package/templates/desktop/docs/docs/api.template.md +320 -320
  129. package/templates/desktop/docs/docs/architecture.template.md +724 -724
  130. package/templates/desktop/docs/docs/business-flows.template.md +102 -102
  131. package/templates/desktop/docs/docs/code-standards.template.md +792 -792
  132. package/templates/desktop/docs/docs/contributing.template.md +149 -149
  133. package/templates/desktop/docs/docs/data-model.template.md +520 -520
  134. package/templates/desktop/docs/docs/operations.template.md +720 -720
  135. package/templates/desktop/docs/docs/testing.template.md +722 -722
  136. package/templates/desktop/project-brief.template.md +150 -150
  137. package/templates/desktop/specs/specs/configuration.template.md +121 -121
  138. package/templates/desktop/specs/specs/security.template.md +392 -392
  139. package/templates/frontend/README.template.md +2 -2
  140. package/templates/frontend/ai-instructions.template.md +2 -2
  141. package/templates/frontend/docs/api-integration.template.md +362 -362
  142. package/templates/frontend/docs/components.template.md +2 -2
  143. package/templates/frontend/docs/error-handling.template.md +360 -360
  144. package/templates/frontend/docs/operations.template.md +107 -107
  145. package/templates/frontend/docs/performance.template.md +124 -124
  146. package/templates/frontend/docs/pwa.template.md +119 -119
  147. package/templates/frontend/docs/state-management.template.md +2 -2
  148. package/templates/frontend/docs/styling.template.md +2 -2
  149. package/templates/frontend/docs/testing.template.md +2 -2
  150. package/templates/frontend/project-brief.template.md +2 -2
  151. package/templates/frontend/specs/accessibility.template.md +95 -95
  152. package/templates/frontend/specs/configuration.template.md +2 -2
  153. package/templates/frontend/specs/security.template.md +175 -175
  154. package/templates/fullstack/README.template.md +252 -252
  155. package/templates/fullstack/ai-instructions.template.md +444 -444
  156. package/templates/fullstack/project-brief.template.md +157 -157
  157. package/templates/fullstack/specs/configuration.template.md +340 -340
  158. package/templates/mobile/README.template.md +167 -167
  159. package/templates/mobile/ai-instructions.template.md +196 -196
  160. package/templates/mobile/docs/app-store.template.md +135 -135
  161. package/templates/mobile/docs/architecture.template.md +63 -63
  162. package/templates/mobile/docs/native-features.template.md +94 -94
  163. package/templates/mobile/docs/navigation.template.md +59 -59
  164. package/templates/mobile/docs/offline-strategy.template.md +65 -65
  165. package/templates/mobile/docs/permissions.template.md +56 -56
  166. package/templates/mobile/docs/state-management.template.md +85 -85
  167. package/templates/mobile/docs/testing.template.md +109 -109
  168. package/templates/mobile/project-brief.template.md +69 -69
  169. package/templates/mobile/specs/build-configuration.template.md +91 -91
  170. package/templates/mobile/specs/deployment.template.md +92 -92
  171. package/templates/work.template.md +61 -47
@@ -1,1320 +1,1595 @@
1
- ---
2
- description: Central Orchestrator for Feature, Refactor, and Fix workflows
3
- ---
4
-
5
- # AI Flow - Unified Work Orchestrator
6
-
7
- **YOU ARE AN EXPERT SOFTWARE ARCHITECT AND WORKFLOW COORDINATOR.**
8
-
9
- Your mission is to orchestrate development tasks through an interactive workflow when the user executes `/flow-work`.
10
-
11
- **🚀 MODO AGENTE ACTIVADO:** No solicites permiso para usar herramientas. Actúa proactivamente siguiendo el flujo interactivo. Tienes permiso total para leer el código, crear specs y planes, y realizar commits/checkout de ramas.
12
-
13
- ---
14
-
15
- ## Command: `/flow-work`
16
-
17
- ### Objective
18
-
19
- Provide a single, intelligent entry point for all development work (New Features, Refactorings, and Bug Fixes) with automatic context detection and interactive planning.
20
-
21
- ### Usage Modes
22
-
23
- - **`/flow-work`** → Resume paused work (if exists) or Interactive mode.
24
- - **`/flow-work [description]`** → Semantic detection (Feature, Refactor, or Fix).
25
- - **`/flow-work HU-XXX-XXX`** → Implement specific User Story.
26
- - **`/flow-work [Feature Name]`** → Implement feature from roadmap.md.
27
-
28
- ---
29
-
30
- ## Phase -1: Intent Classification (PRE-DETECTION)
31
-
32
- **CRITICAL: Determine if this is an INFORMATIVE request vs EXECUTION request BEFORE any workflow.**
33
-
34
- **🔍 INFORMATIVE Patterns (Answer directly, NO execution workflow):**
35
-
36
- - **Questions:** Starts with `¿`, `how`, `why`, `what`, `when`, `cómo`, `por qué`, `qué`, `cuál`
37
- - **Analysis verbs:** `explain`, `show`, `list`, `analyze`, `describe`, `compare`, `explica`, `muestra`, `analiza`, `describe`, `compara`
38
- - **Report requests:** `report`, `informe`, `document`, `documenta`, `summary`, `resumen`, `generate report`, `genera informe`
39
- - **Exploration:** `find`, `search`, `busca`, `encuentra`, `where is`, `dónde está`
40
- - **Review requests:** `review`, `revisa`, `check`, `verifica`, `audit`, `audita`
41
-
42
- **🛠️ EXECUTION Patterns (Enter workflow):**
43
-
44
- - **Action verbs:** `implement`, `create`, `refactor`, `fix`, `add`, `remove`, `update`, `delete`, `build`, `develop`
45
- - **Task codes:** `HU-\d{3}-\d{3}`, `EP-\d{3}`, `T\d{3}`
46
- - **Imperative:** `new feature`, `nueva feature`, `crear`, `implementar`
47
-
48
- **Detection Logic:**
49
-
50
- ```python
51
- import re
52
-
53
- # Normalize input
54
- input_lower = input.strip().lower()
55
-
56
- # INFORMATIVE patterns (high priority)
57
- informative_patterns = [
58
- r'^(¿|how|why|what|when|where|cómo|por qué|qué|cuál|dónde)',
59
- r'^(explain|show|list|analyze|describe|compare|explica|muestra|analiza|describe|compara)',
60
- r'(report|informe|document|documenta|summary|resumen)',
61
- r'(find|search|busca|encuentra)',
62
- r'(review|revisa|check|verifica|audit|audita)',
63
- ]
64
-
65
- for pattern in informative_patterns:
66
- if re.search(pattern, input_lower):
67
- return "INFORMATIVE" # → Jump to Phase 99
68
-
69
- # EXECUTION patterns
70
- execution_patterns = [
71
- r'(HU-\d{3}-\d{3}|EP-\d{3}|T\d{3})', # Task codes
72
- r'^(implement|create|refactor|fix|add|remove|update|delete|build|develop)',
73
- r'(implementar|crear|nueva feature|new feature)',
74
- ]
75
-
76
- for pattern in execution_patterns:
77
- if re.search(pattern, input_lower):
78
- return "EXECUTION" # → Continue to Phase 0
79
-
80
- # Ambiguous case - ask user
81
- return "AMBIGUOUS"
82
- ```
83
-
84
- **Action based on detection:**
85
-
86
- **IF mode == "INFORMATIVE":**
87
-
88
- ```
89
- 🔍 Detected: Informative request (question/report/analysis)
90
-
91
- I'll provide a detailed answer without creating work files or branches.
92
- ```
93
-
94
- → **Jump to Phase 99: Informative Response**
95
-
96
- **IF mode == "EXECUTION":**
97
-
98
- → **Continue to Phase 0** (current workflow)
99
-
100
- **IF mode == "AMBIGUOUS":**
101
-
102
- ```
103
- ❓ I'm not sure if this is:
104
- A) A question/report request (I'll answer directly)
105
- B) A task to implement (I'll create work plan and execute)
106
-
107
- Please clarify (A/B): _
108
- ```
109
-
110
- ---
111
-
112
- ## Phase 0: Detection & Strategy (Automatic)
113
-
114
- **1. Semantic Analysis of Input:**
115
-
116
- | Input Pattern | Mode | Source / Action |
117
- | ------------------------------ | ----------------- | -------------------------------------------------------------------- |
118
- | `HU-\d{3}-\d{3}` | `USER_STORY` | Load from `planning/user-stories/**/HU-XXX-XXX.md` |
119
- | `EP-\d{3}` | `EPIC` | Analyze/List User Stories for Epic `EP-XXX` |
120
- | `T\d{3}(-T\d{3})?` | `TASKS` | Target specific task or range (e.g., `T025-T030`) |
121
- | `HU-XXX-XXX TXXX-TXXX` | `STORY_TASKS` | Targeted tasks within a specific User Story |
122
- | Matches `planning/roadmap.md` | `ROADMAP_FEATURE` | Extract section from `planning/roadmap.md` (Partial matches allowed) |
123
- | "refactor", "move", "extract" | `REFACTOR` | Use `flow-work-refactor.md` |
124
- | "fix", "bug", "error", "falla" | `FIX` | Detect complexity (Quick vs Complex) |
125
- | "implement", "create", "new" | `FEATURE` | Use `flow-work-feature.md` |
126
- | No arguments | `RESUME` | Search for paused work in `.ai-flow/work/` |
127
-
128
- **2. Detection Logic Details:**
129
-
130
- - **USER_STORY / EPIC**: Load metadata from `planning/user-stories/` or `planning/roadmap.md`.
131
- - **ROADMAP_FEATURE**: Fuzzy search in `planning/roadmap.md` for titles like "User Management" or "Feature 2.2".
132
- - **TASK RANGES**: If `T025-T030` is provided, find the parent Story or Feature in current context or roadmap.
133
- - **SIMPLE FIX**: Affects 1 file, obvious cause, <10 lines fix. Use `flow-work-fix.md` (Quick).
134
- - **COMPLEX FIX**: Multi-file, architectural, performance/security. → Use `flow-work-fix.md` (Deep).
135
-
136
- ---
137
-
138
- ## Phase 0.5: Complexity Classification (CRITICAL)
139
-
140
- **Analyze task scope to determine workflow:**
141
-
142
- | Metric | SIMPLE (⚡) | MEDIUM (📝) | COMPLEX (🏗️) |
143
- | ------------- | ----------- | ----------- | ------------- |
144
- | Files | 1 | 2-5 | >5 |
145
- | Lines | <20 | 20-100 | >100 |
146
- | Tests | No | Optional | Required |
147
- | Docs | None | Minor | Significant |
148
- | Architecture | None | Minimal | Major changes |
149
- | Time estimate | <15 min | 15-60 min | >60 min |
150
-
151
- **Classification Rules:**
152
-
153
- **⚡ SIMPLE Task:**
154
-
155
- - Examples: Fix typo, rename variable, update constant, add log, adjust CSS
156
- - **Workflow**: In-chat plan → Execute → Done (NO files created)
157
- - **Context**: Only `ai-instructions.md` if relevant
158
-
159
- **📝 MEDIUM Task:**
160
-
161
- - Examples: Add component, refactor hook, simple bug fix, update API call
162
- - **Workflow**: Create `work.md` only (NO `status.json`) → Execute → Simple archive
163
- - **Context**: Load 2-3 relevant docs
164
-
165
- **🏗️ COMPLEX Task:**
166
-
167
- - Examples: New feature, major refactor, security fix, multi-file changes
168
- - **Workflow**: Full workflow (`work.md` + `status.json` + branch + archiving)
169
- - **Context**: Load all relevant docs
170
-
171
- **Detection Logic:**
172
-
173
- ```python
174
- if files_affected == 1 and lines_changed < 20 and no_tests_needed and no_architecture_impact:
175
- complexity = "SIMPLE"
176
- elif files_affected <= 5 and lines_changed <= 100 and architecture_impact == "minimal":
177
- complexity = "MEDIUM"
178
- else:
179
- complexity = "COMPLEX"
180
- ```
181
-
182
- **Show classification:**
183
-
184
- ```
185
- 🔍 Task Complexity: [SIMPLE | MEDIUM 📝 | COMPLEX 🏗️]
186
-
187
- Detected:
188
- - Files: [N]
189
- - Estimated lines: [~X]
190
- - Tests needed: [Yes/No]
191
- - Architecture impact: [None/Minimal/Major]
192
-
193
- Proceeding with [SIMPLE/MEDIUM/COMPLEX] workflow.
194
- ```
195
-
196
- ---
197
-
198
- ## Phase 1: Analysis & Refinement
199
-
200
- **1. Context Loading (Smart & Selective):**
201
-
202
- **CRITICAL: Load context based on task complexity and type:**
203
-
204
- **IF complexity == "SIMPLE":**
205
-
206
- - Load ONLY `ai-instructions.md` if task involves code changes
207
- - Skip all other documentation
208
- - Use existing patterns in nearby code as reference
209
-
210
- **IF complexity == "MEDIUM":**
211
-
212
- - Load `ai-instructions.md` (core rules)
213
- - Load 1-2 specific docs based on task type:
214
- - Component changes → `docs/components.md`
215
- - Routing changes `docs/routing.md`
216
- - State management → `docs/state-management.md`
217
- - Styling → `docs/styling.md`
218
- - Skip architecture.md unless creating new patterns
219
-
220
- **IF complexity == "COMPLEX":**
221
-
222
- - Load `ai-instructions.md` (NEVER/ALWAYS rules)
223
- - Load `docs/architecture.md` (patterns, structure)
224
- - Load task-specific docs:
225
- - Components → `docs/components.md`
226
- - Routing/Navigation `docs/routing.md`
227
- - State `docs/state-management.md`
228
- - API Integration → `docs/api-integration.md`
229
- - Testing `docs/testing.md`
230
- - Load `docs/code-standards.md` only if creating new files
231
-
232
- **Source Documentation (User Stories/Roadmap):**
233
-
234
- **IF** `HU-XXX-XXX` or roadmap feature provided:
235
-
236
- - **`planning/roadmap.md`**: Load for high-level scope
237
- - **`planning/user-stories/**/HU-XXX-XXX.md`\*\*: Load for detailed requirements
238
-
239
- **2. Detail Level Detection (if Manual input):**
240
-
241
- IF input is manual description (not HU/Roadmap):
242
-
243
- ```python
244
- detail_level = analyze_description(input)
245
-
246
- # Criteria for HIGH detail (Feature):
247
- # - Mentions technology/method (JWT, OAuth, bcrypt, etc.)
248
- # - Describes flow (registration, login, CRUD, etc.)
249
- # - Includes technical constraints (hashing, tokens, validation, etc.)
250
-
251
- # Criteria for HIGH detail (Refactor):
252
- # - Describes what to extract/move
253
- # - Mentions destination (file/class)
254
- # - References pattern to follow
255
-
256
- # Criteria for HIGH detail (Fix):
257
- # - Describes symptom (error 500, crash, null pointer, etc.)
258
- # - Mentions probable cause
259
- # - Suggests fix approach
260
- ```
261
-
262
- **3. Interactive Refinement (Conditional):**
263
-
264
- **IF detail_level == "HIGH":**
265
-
266
- - Skip refinement questions
267
- - Proceed directly to Phase 2 (Planning)
268
- - Show: "✅ Sufficient detail detected. Proceeding with planning..."
269
-
270
- **IF detail_level == "MEDIUM":**
271
-
272
- - Ask 1-2 targeted questions (only missing items)
273
- - Use Multiple Choice with defaults (⭐)
274
-
275
- **IF detail_level == "LOW":**
276
-
277
- - Full refinement flow (3-5 questions)
278
- - Use Multiple Choice with defaults (⭐)
279
- - Focus on: approach, scope, constraints, priorities
280
-
281
- **Example Interaction (LOW detail):**
282
-
283
- > 📝 I need to clarify some details for this feature:
284
- >
285
- > 1. What authentication provider should we use? [default: A]
286
- > A) JWT (Local)
287
- > B) OAuth2 (Google/GitHub)
288
- > C) Firebase Auth
289
- > 2. Should we implement audit logs for this? [default: B]
290
- > A) Yes
291
- > B) No ⭐
292
- >
293
- > Your answers (or Enter for defaults): \_
294
-
295
- **4. Refined Objective Generation (if Manual):**
296
-
297
- After refinement, generate clear objective statement:
298
-
299
- ```
300
- ✅ Refined Objective:
301
-
302
- [Clear 1-2 paragraph description of WHAT will be implemented]
303
-
304
- **Scope**:
305
- - [List in-scope items]
306
-
307
- **Out of Scope**:
308
- - [List out-of-scope items]
309
-
310
- Is this correct? (Yes/Edit/Cancel): _
311
- ```
312
-
313
- **5. Documentation Compliance Check:**
314
-
315
- Read relevant documentation:
316
-
317
- - `ai-instructions.md` (NEVER/ALWAYS rules)
318
- - `docs/architecture.md` (patterns, structure)
319
- - `docs/code-standards.md` (naming, quality)
320
- - IF auth/security: `specs/security.md`
321
- - IF database: `docs/data-model.md`
322
- - IF API: `docs/api.md`
323
-
324
- Compare refined objective against documentation:
325
-
326
- **IF deviation detected:**
327
-
328
- ```
329
- 🚨 POTENTIAL DEVIATION
330
-
331
- From [document]:
332
- NEVER: [rule being violated]
333
- ALWAYS: [rule being ignored]
334
-
335
- Your request: [conflicting part]
336
-
337
- Options:
338
- A) Modify request to align with documentation
339
- B) Proceed with deviation (requires justification)
340
- C) Cancel
341
-
342
- Your choice: _
343
- ```
344
-
345
- **IF user chooses B (Override):**
346
-
347
- ```
348
- ⚠️ OVERRIDE CONFIRMATION
349
-
350
- You are implementing something that deviates from:
351
- - [list violated documents/rules]
352
-
353
- Type "I UNDERSTAND THE RISKS" to proceed: _
354
-
355
- Provide justification: _
356
- ```
357
-
358
- ---
359
-
360
- ## Phase 1.5: SIMPLE Task Fast-Track
361
-
362
- **IF complexity == "SIMPLE": Execute immediately without creating files**
363
-
364
- 1. **Show in-chat plan:**
365
-
366
- ```
367
- SIMPLE Task - Fast Execution
368
-
369
- What: [1-line description]
370
- File: [path]
371
- Change: [specific modification]
372
- Lines: ~[N] (estimated)
373
-
374
- Execute now? (y/n): _
375
- ```
376
-
377
- 2. **IF user confirms ('y'):**
378
- - Make the change immediately
379
- - Show git diff preview
380
- - Skip to Phase 3 (no branch creation if already on feature branch)
381
- - Show: "✅ Done. Run `/flow-commit` to commit."
382
- - **END WORKFLOW** (no archiving needed)
383
-
384
- 3. **IF user declines ('n'):**
385
- - Cancel task
386
- - **END WORKFLOW**
387
-
388
- **Note:** SIMPLE tasks don't create work.md, status.json, or archive records.
389
-
390
- ---
391
-
392
- ## Phase 2: Planning & Documentation
393
-
394
- **⚠️ SKIP THIS PHASE IF complexity == "SIMPLE"**
395
-
396
- **1. Read Required Documentation (Based on Complexity)**
397
-
398
- **IF complexity == "MEDIUM":**
399
-
400
- - `ai-instructions.md` (core rules)
401
- - Load ONLY task-specific docs:
402
- - Components → `docs/components.md`
403
- - Routing `docs/routing.md`
404
- - State `docs/state-management.md`
405
- - Styling → `docs/styling.md`
406
-
407
- **IF complexity == "COMPLEX":**
408
-
409
- - `ai-instructions.md` (NEVER/ALWAYS rules)
410
- - `docs/architecture.md` (layer, pattern, structure)
411
- - Task-specific docs:
412
- - Components → `docs/components.md`
413
- - Routing/Navigation `docs/routing.md`
414
- - State `docs/state-management.md`
415
- - API Integration → `docs/api-integration.md`
416
- - Testing → `docs/testing.md`
417
- - `docs/code-standards.md` (only if creating new files)
418
-
419
- **2. Analyze Existing Codebase (MANDATORY)**
420
-
421
- Find similar features/patterns in codebase:
422
-
423
- - Identify existing files to use as reference (e.g., UserProfile.tsx for ProductCard.tsx)
424
- - Check naming conventions in actual code
425
- - Verify architectural consistency
426
- - Look for reusable components/hooks
427
-
428
- **3. Generate work.md (Conditional)**
429
-
430
- **IF complexity == "MEDIUM":**
431
-
432
- - Create simplified `.ai-flow/work/[task-name]/work.md` (~15-20 lines)
433
- - Skip status.json
434
-
435
- **IF complexity == "COMPLEX":**
436
-
437
- - Create full `.ai-flow/work/[task-name]/work.md` (~30-40 lines)
438
- - Create `status.json` (see step 4)
439
-
440
- **Structure for MEDIUM tasks** (~15-20 lines):
441
-
442
- ```markdown
443
- # [Type]: [Feature Name]
444
-
445
- **Source**: [HU-XXX | Roadmap X.X | Manual]
446
- **Files**: [2-5 files listed]
447
- **Estimated**: [20-60 min]
448
-
449
- ## Objective
450
-
451
- [1 clear paragraph]
452
-
453
- ## Tasks
454
-
455
- - [ ] Task 1 → path/Component.tsx
456
- - [ ] Task 2 path/hook.ts
457
- - [ ] Task 3 (optional tests)
458
-
459
- ## Key Rules
460
-
461
- - [1-2 relevant ALWAYS rules]
462
- - [1-2 relevant NEVER rules]
463
- ```
464
-
465
- **Structure for COMPLEX tasks** (~30-40 lines):
466
-
467
- ```markdown
468
- # [Type]: [Feature Name]
469
-
470
- ## Context
471
-
472
- **Source**: HU-001-002 | Roadmap 2.3 | Manual [+ DEVIATION if override]
473
- **SP**: 5 | **Branch**: feature/user-auth | **Deps**: None
474
-
475
- ## Objective
476
-
477
- [1-2 clear paragraphs describing WHAT will be implemented]
478
-
479
- ## Documentation Constraints
480
-
481
- **Read**: ai-instructions.md, architecture.md, code-standards.md, [security.md]
482
-
483
- **Key Rules**:
484
-
485
- - ALWAYS: [List specific rules that apply]
486
- - NEVER: [List specific prohibitions]
487
- - 📐 Pattern: [Architectural pattern from docs]
488
- - 📁 Location: [File structure from architecture.md]
489
-
490
- ## Approach
491
-
492
- **Layer**: [Data | Business Logic | API | UI]
493
- **Files**: [List files to create/modify]
494
- **Reference**: [Existing file to follow as pattern]
495
-
496
- **Phases**:
497
-
498
- 1. [Phase 1 description]
499
- 2. [Phase 2 description]
500
- 3. [Phase 3 description]
501
- 4. [Phase 4 description]
502
-
503
- ## Tasks
504
-
505
- [SEE TASK GENERATION LOGIC BELOW]
506
-
507
- ## Validation
508
-
509
- - [ ] All NEVER/ALWAYS rules followed
510
- - [ ] Tests pass (coverage per docs/testing.md)
511
- - [ ] No hardcoded secrets
512
- - [ ] Follows existing patterns
513
- - [ ] [Add specific validations based on type]
514
- ```
515
-
516
- **Task Generation Logic:**
517
-
518
- **IF source is User Story:**
519
-
520
- ```python
521
- tasks = read_user_story_tasks()
522
- if tasks.are_detailed(): # Has: path, constraints, SP, deps
523
- work_md.tasks = """
524
- **Source**: planning/user-stories/EP-XXX/HU-XXX-XXX.md
525
-
526
- Tasks already detailed in User Story (see linked file).
527
-
528
- **Summary**: [N] tasks, [X] SP total
529
- - [Brief phase breakdown]
530
- """
531
- else:
532
- work_md.tasks = generate_detailed_tasks()
533
- ```
534
-
535
- **IF source is Roadmap:**
536
-
537
- ```python
538
- feature = read_roadmap_feature()
539
- if feature.has_detailed_tasks():
540
- work_md.tasks = """
541
- **Source**: planning/roadmap.md Feature X.X
542
-
543
- Tasks already detailed in Roadmap (see linked file).
544
-
545
- **Summary**: [N] tasks, [X] SP total
546
- """
547
- else:
548
- work_md.tasks = generate_detailed_tasks()
549
- ```
550
-
551
- **IF source is Manual OR tasks need expansion:**
552
-
553
- Generate detailed tasks with this format:
554
-
555
- ```markdown
556
- ## Tasks
557
-
558
- **Source**: Manual | Roadmap X.X (expanded) | HU-XXX-XXX (expanded)
559
-
560
- - [ ] T001 [D] Create User entity → src/entities/User.ts • 1 SP
561
- - Follow Product.ts pattern, hash passwords (bcrypt)
562
- - [ ] T002 [L] UserService.register() → src/services/ • 2 SP
563
- - Validate email, hash password, return JWT (deps: T001)
564
- - [ ] T003 [A] POST /users/register → src/controllers/ • 1 SP
565
- - Return 201, rate limit, follow api.md (deps: T002)
566
- - [ ] T004 [T] Unit tests → tests/services/ • 2 SP
567
- - 80% coverage, edge cases (deps: T002)
568
- ```
569
-
570
- **Task Detail Requirements:**
571
-
572
- - Specific file path
573
- - Pattern/reference to follow
574
- - Key constraints from docs
575
- - Dependencies (if applicable)
576
- - Story Points
577
-
578
- **4. Generate status.json (ONLY for COMPLEX tasks)**
579
-
580
- **IF complexity == "COMPLEX":**
581
-
582
- Create: `.ai-flow/work/[task-name]/status.json`
583
-
584
- ```json
585
- {
586
- "type": "feature|refactor|fix",
587
- "source": "HU-001-002|roadmap-2.3|manual",
588
- "deviation": false,
589
- "progress": {
590
- "totalTasks": 4,
591
- "completedTasks": 0,
592
- "percentage": 0
593
- },
594
- "git": {
595
- "branchName": "feature/user-auth",
596
- "commits": []
597
- },
598
- "timestamps": {
599
- "created": "2025-12-22T23:00:00-03:00",
600
- "lastUpdated": "2025-12-22T23:00:00-03:00"
601
- },
602
- "validation": {
603
- "tests": { "executed": false },
604
- "lint": { "executed": false }
605
- }
606
- }
607
- ```
608
-
609
- **5. User Approval**
610
-
611
- Show work.md for review:
612
-
613
- ```
614
- 📄 Generated: .ai-flow/work/[task-name]/work.md
615
-
616
- Review work.md? (Yes/Edit/No): _
617
- ```
618
-
619
- - **Yes**: Proceed to Phase 3
620
- - **Edit**: Allow user to modify work.md, then re-read
621
- - **No**: Cancel workflow
622
-
623
- ---
624
-
625
- ## Phase 3: Execution (Branch Creation)
626
-
627
- **Upon confirmation to start implementation:**
628
-
629
- **🛡️ CRITICAL: Protected Branch Check**
630
-
631
- ```bash
632
- git branch --show-current
633
- git status --porcelain
634
- ```
635
-
636
- **If current branch is protected** (`main`, `master`, `develop`, `development`):
637
-
638
- **A) If there are uncommitted changes:**
639
-
640
- 1. **Analyze changes to generate branch name:**
641
-
642
- ```bash
643
- git status --porcelain
644
- git diff --stat
645
- ```
646
-
647
- **Detection rules:**
648
- - **New components/features** → `feature/`
649
- - **Bug fixes** (error handling, corrections) → `fix/`
650
- - **Refactoring/Styling** (code improvements, CSS changes) → `refactor/`
651
- - **Configuration/Dependencies** (package.json, webpack, vite, etc.) → `chore/`
652
- - **Tests only** → `test/`
653
- - **Documentation only** → `docs/`
654
-
655
- **Naming strategy:**
656
- - Extract component/page/feature name
657
- - Remove extensions (.tsx, .jsx, .ts, .js)
658
- - Convert to kebab-case
659
- - Limit to 3-4 words max
660
-
661
- **Examples:**
662
-
663
- ```
664
- src/components/UserProfile.tsx (new) → feature/user-profile
665
- src/pages/Dashboard.tsx (fix) → fix/dashboard-page
666
- src/hooks/useAuth.ts (modified) → refactor/use-auth-hook
667
- package.json + package-lock.json → chore/update-dependencies
668
- src/components/Auth* + src/pages/Login* → feature/authentication
669
- styles/ + components/ (multiple) → refactor/ui-components
670
- ```
671
-
672
- 2. **Warn user:**
673
-
674
- ```
675
- ⚠️ Working on protected branch '[branch-name]' with uncommitted changes.
676
-
677
- Analyzed changes:
678
- - [file1] (new)
679
- - [file2] (modified)
680
- - [file3] (modified)
681
- ... [N] more files
682
-
683
- Detected type: [feature|fix|refactor|chore]
684
- Suggested branch: [type]/[descriptive-slug]
685
- ```
686
-
687
- 3. **Offer options:**
688
- - **A)** Create branch: `[type]/[suggested-name]` ⭐
689
- - **B)** Edit branch name (user provides custom slug)
690
- - **C)** Stash changes and continue: `git stash`
691
- - **D)** Cancel
692
-
693
- 4. If user chooses A:
694
-
695
- ```bash
696
- git checkout -b [type]/[suggested-name]
697
- ```
698
-
699
- Then show:
700
-
701
- ```
702
- Created and switched to '[type]/[suggested-name]'
703
-
704
- Next steps:
705
- 1. Run /flow-commit to commit these changes
706
- 2. Return to protected branch: git checkout [protected-branch]
707
- 3. Continue with /flow-work for new task
708
-
709
- Or continue working on this branch if it's your intended work.
710
- ```
711
-
712
- 5. If user chooses B:
713
- ```
714
- Enter branch name (without type prefix): _
715
- ```
716
- Then create: `[detected-type]/[user-input]`
717
-
718
- **B) If NO uncommitted changes:**
719
-
720
- - Proceed normally - creating work branches FROM protected branches is correct workflow
721
- - Protected branches serve as base for new work
722
-
723
- 1. **Generate Branch Name**:
724
- - `feature/[slug]`
725
- - `refactor/[slug]`
726
- - `fix/[slug]`
727
- 2. **Execute**: `git checkout -b [branch-name]`.
728
- 3. **Update `status.json`**: Record branch name and start timestamp.
729
- 4. **Implementation**: Proceed according to the selected mode (Auto, Phase-by-phase, Task-by-task).
730
- - Follow tasks in `work.md`
731
- - Update task checkboxes as completed
732
- - Update `status.json` progress
733
-
734
- ---
735
-
736
- ## Phase 4: Finalization (User-Controlled)
737
-
738
- **⚠️ SKIP THIS PHASE IF complexity == "SIMPLE"** (already handled in Phase 1.5)
739
-
740
- **Trigger Options:**
741
-
742
- - User types: `/flow-work complete`
743
- - All checkboxes in work.md marked complete
744
- - User explicitly requests finalization
745
-
746
- **CRITICAL: This phase requires EXPLICIT user confirmations at each step.**
747
-
748
- ---
749
-
750
- ### Step 1: Validation Check
751
-
752
- ```
753
- 🔍 Running validation...
754
- ```
755
-
756
- Execute:
757
-
758
- ```bash
759
- npm test # or project-specific test command
760
- npm run lint # or project-specific lint command
761
- ```
762
-
763
- Show results:
764
-
765
- ```
766
- 📊 Validation Results
767
-
768
- Tests: [✅ Passed | ❌ Failed (N tests)]
769
- Lint: [✅ Clean | ⚠️ N warnings | ❌ N errors]
770
- Coverage: [X%]
771
-
772
- Proceed with finalization?
773
-
774
- a) Yes, continue ⭐
775
- b) No, let me fix issues
776
- c) Skip validation (not recommended)
777
-
778
- Your choice: _
779
- ```
780
-
781
- - **'b'**: Return to Phase 3 for fixes, END finalization
782
- - **'c'**: Show warning, ask confirmation again, then continue
783
- - **'a'**: Continue to Step 2
784
-
785
- ---
786
-
787
- ### Step 2: Source Documentation Update (Interactive)
788
-
789
- **Detect source references:**
790
-
791
- ```python
792
- source = extract_from_work_md_or_status_json()
793
- # Returns: "HU-001-002" | "roadmap-2.3" | "manual" | None
794
- ```
795
-
796
- **IF source exists (HU or roadmap):**
797
-
798
- ```
799
- 📚 Update Source Documentation?
800
-
801
- Found:
802
- - planning/roadmap.md → Feature 2.3 "User Profile Component"
803
- - planning/user-stories/EP-001/HU-001-002.md
804
-
805
- What to update?
806
-
807
- a) Update both
808
- b) Update roadmap only
809
- c) Update user story only
810
- d) Skip (I'll update manually later)
811
-
812
- Your choice: _
813
- ```
814
-
815
- **Execute selected updates:**
816
-
817
- - Read files
818
- - Mark checkboxes as complete: `- [ ]` `- [x]`
819
- - Add timestamp comment: `<!-- Completed: YYYY-MM-DD HH:MM -->`
820
- - Save files
821
-
822
- **Show confirmation:**
823
-
824
- ```
825
- Updated:
826
- - planning/roadmap.md (Feature 2.3)
827
- - planning/user-stories/EP-001/HU-001-002.md (5/5 DoD items)
828
- ```
829
-
830
- **IF update fails:**
831
-
832
- ```
833
- Failed to update [file]: [reason]
834
-
835
- Options:
836
- 1) Retry update
837
- 2) Skip this file
838
- 3) Cancel finalization
839
-
840
- Your choice: _
841
- ```
842
-
843
- **IF source is "manual" or None:**
844
-
845
- ```
846
- ⏭️ No source documentation to update (manual task)
847
- ```
848
-
849
- ---
850
-
851
- ### Step 3: Archiving Decision (Explicit Confirmation)
852
-
853
- **Show current state:**
854
-
855
- ```bash
856
- git diff --stat
857
- git log --oneline origin/[base-branch]..HEAD
858
- ```
859
-
860
- **Present archiving options:**
861
-
862
- ```
863
- 💾 Task Completion Options
864
-
865
- Current work:
866
- - Branch: [branch-name]
867
- - Files changed: [N]
868
- - Commits: [N]
869
- - Duration: [X min]
870
-
871
- What do you want to do?
872
-
873
- a) Complete & Archive
874
- → Record analytics, delete work files, clean state
875
-
876
- b) Complete & Keep
877
- Record analytics, rename folder to [task]-completed
878
-
879
- c) Mark as Paused
880
- Keep work files for later resume
881
-
882
- d) Cancel
883
- → Go back to editing
884
-
885
- Your choice: _
886
- ```
887
-
888
- **IF 'a' (Complete & Archive):**
889
-
890
- ```
891
- Archiving task...
892
- ```
893
-
894
- 1. **Extract metadata:**
895
-
896
- ```javascript
897
- // IF complexity == "COMPLEX" (has status.json):
898
- analytics = {
899
- task: '[task-name]',
900
- type: '[feature|refactor|fix]',
901
- src: '[HU-001-002|roadmap-2.3|manual]',
902
- dur: Math.round((completed - created) / 60000), // minutes
903
- start: timestamps.created,
904
- end: new Date().toISOString(),
905
- tasks: progress.totalTasks,
906
- sp: extract_story_points_from_work_md(),
907
- commits: git.commits.length,
908
- valid: validation.tests.passed && validation.lint.passed,
909
- };
910
-
911
- // IF complexity == "MEDIUM" (only work.md):
912
- analytics = {
913
- task: '[task-name]',
914
- type: '[detected-from-folder-name]',
915
- src: 'manual',
916
- dur: estimate_duration_from_git_log(),
917
- start: get_first_commit_timestamp(),
918
- end: new Date().toISOString(),
919
- tasks: count_checkboxes_in_work_md(),
920
- sp: extract_story_points_from_work_md() || null,
921
- commits: count_commits_in_branch(),
922
- valid: validation_passed,
923
- };
924
- ```
925
-
926
- 2. **Append to analytics:**
927
-
928
- ```bash
929
- echo '{json}' >> .ai-flow/archive/analytics.jsonl
930
- ```
931
-
932
- 3. **Delete work folder:**
933
-
934
- ```bash
935
- rm -rf .ai-flow/work/[task-name]/
936
- ```
937
-
938
- 4. **Show confirmation:**
939
-
940
- ```
941
- ✅ Task archived successfully
942
-
943
- 📊 Analytics recorded:
944
- - Duration: [X] min
945
- - Story Points: [N]
946
- - Commits: [N]
947
- - Validation: [✅ Passed | ❌ Failed]
948
- ```
949
-
950
- **IF 'b' (Complete & Keep):**
951
-
952
- 1. Record analytics (same as 'a')
953
- 2. Rename folder:
954
- ```bash
955
- mv .ai-flow/work/[task] .ai-flow/work/[task]-completed/
956
- ```
957
- 3. Show: `✅ Task marked complete. Files kept in: .ai-flow/work/[task]-completed/`
958
-
959
- **IF 'c' (Mark as Paused):**
960
-
961
- 1. Add marker file:
962
- ```bash
963
- echo "Paused: $(date)" > .ai-flow/work/[task]/PAUSED
964
- ```
965
- 2. Show: `⏸️ Task paused. Resume with: /flow-work`
966
- 3. **END finalization**
967
-
968
- **IF 'd' (Cancel):**
969
-
970
- 1. Show: `❌ Finalization cancelled. Task remains active.`
971
- 2. **END finalization**
972
-
973
- ---
974
-
975
- ### Step 4: Ticket Summary (Optional)
976
-
977
- **Only ask if task was archived (option 'a' or 'b'):**
978
-
979
- ```
980
- 📋 Generate ticket summary?
981
-
982
- (For ClickUp, Jira, Linear, Asana, Trello, GitHub Projects, etc.)
983
-
984
- y/n: _
985
- ```
986
-
987
- **IF 'y':**
988
-
989
- 1. Check if template exists:
990
-
991
- ```bash
992
- [ -f .ai-flow/prompts/shared/task-summary-template.md ]
993
- ```
994
-
995
- 2. **IF template exists:**
996
- - Read template
997
- - Extract data from:
998
- - Last line of `analytics.jsonl`
999
- - Git stats: `git diff --stat`, `git log --oneline`
1000
- - Branch info
1001
- - Populate template with real data
1002
- - Show formatted summary
1003
-
1004
- 3. **IF template doesn't exist:**
1005
- - Generate basic summary:
1006
-
1007
- ```
1008
- 📋 Task Summary
1009
-
1010
- **Task**: [task-name]
1011
- **Type**: [feature|refactor|fix]
1012
- **Duration**: [X min]
1013
- **Story Points**: [N]
1014
- **Commits**: [N]
1015
- **Branch**: [branch-name]
1016
- **Status**: Complete
1017
-
1018
- **Changes**:
1019
- [git diff --stat output]
1020
-
1021
- **Commits**:
1022
- [git log --oneline output]
1023
- ```
1024
-
1025
- 4. Show: `📋 Copy the summary above to your ticket system`
1026
-
1027
- **IF 'n':**
1028
-
1029
- ```
1030
- ⏭️ Skipping ticket summary
1031
- ```
1032
-
1033
- ---
1034
-
1035
- ### Step 5: Git Push (Final Step)
1036
-
1037
- ```
1038
- 🚀 Push changes to remote?
1039
-
1040
- git push origin [branch-name]
1041
-
1042
- y/n: _
1043
- ```
1044
-
1045
- **IF 'y':**
1046
-
1047
- ```bash
1048
- git push origin [branch-name]
1049
- ```
1050
-
1051
- Show result:
1052
-
1053
- ```
1054
- Pushed to origin/[branch-name]
1055
-
1056
- Next steps:
1057
- - Create Pull Request/Merge Request
1058
- - Request code review
1059
- - Update project board
1060
- ```
1061
-
1062
- **IF 'n':**
1063
-
1064
- ```
1065
- ⏭️ Skipping push
1066
-
1067
- ⚠️ Remember to push later:
1068
- git push origin [branch-name]
1069
- ```
1070
-
1071
- ---
1072
-
1073
- ### Finalization Complete
1074
-
1075
- ```
1076
- ✅ Task Finalization Complete
1077
-
1078
- 📊 Summary:
1079
- - [✅|⚠️] Validation passed
1080
- - [✅|⏭️] Documentation updated
1081
- - [✅|⏭️] Task archived
1082
- - [✅|⏭️] Ticket summary generated
1083
- - [✅|⏭️] Pushed to remote
1084
-
1085
- Task: [task-name]
1086
- Branch: [branch-name]
1087
- Duration: [X min]
1088
- Commits: [N]
1089
-
1090
- 🎉 Great work!
1091
- ```
1092
-
1093
- **END WORKFLOW**
1094
-
1095
- ---
1096
-
1097
- ## Orchestration Rules
1098
-
1099
- - **DRY Logic**: This file handles the high-level orchestration.
1100
- - **Delegation**:
1101
- - Detailed Feature logic `@flow-work-feature.md`
1102
- - Detailed Refactor logic → `@flow-work-refactor.md`
1103
- - Detailed Fix logic `@flow-work-fix.md`
1104
- - Resume logic → `@flow-work-resume.md`
1105
- - **State Persistence**: Always read/write to `.ai-flow/work/[name]/status.json` to maintain state across sessions.
1106
-
1107
- ---
1108
-
1109
- ## Phase 99: Informative Response
1110
-
1111
- **This phase handles questions, reports, and analysis requests WITHOUT creating work files or branches.**
1112
-
1113
- ### 1. Analyze Request Type
1114
-
1115
- **Classify the informative request:**
1116
-
1117
- - **Technical Question:** How does X work? Why do we use Y?
1118
- - **Component Explanation:** Explain this component/hook/utility
1119
- - **Architecture Review:** Show me the component structure/state management
1120
- - **Project Report:** Generate report on bundle size/dependencies/performance
1121
- - **File Location:** Where is X component? Find Y hook
1122
- - **Comparison:** Compare X vs Y approach
1123
- - **Best Practices:** What's the best way to do X in React/Vue/Angular?
1124
-
1125
- ### 2. Load Relevant Context
1126
-
1127
- **Based on request type, load specific documentation:**
1128
-
1129
- **IF question about architecture/patterns:**
1130
-
1131
- - Read `ai-instructions.md` (NEVER/ALWAYS rules)
1132
- - Read `docs/architecture.md` (component structure, state management)
1133
- - Search codebase for examples
1134
-
1135
- **IF question about specific component:**
1136
-
1137
- - Search codebase for component files
1138
- - Read relevant specs from `specs/`
1139
- - Check related hooks/utilities
1140
-
1141
- **IF report request:**
1142
-
1143
- - Run appropriate analysis (bundle size, performance, dependencies)
1144
- - Read relevant docs for context
1145
- - Generate structured report
1146
-
1147
- **IF file location request:**
1148
-
1149
- - Search codebase with grep/semantic search
1150
- - List relevant components with descriptions
1151
-
1152
- ### 3. Provide Comprehensive Answer
1153
-
1154
- **Structure your response:**
1155
-
1156
- ```markdown
1157
- ## [Question/Request]
1158
-
1159
- ### Answer
1160
-
1161
- [Detailed explanation with code examples if relevant]
1162
-
1163
- ### Related Documentation
1164
-
1165
- - [Link to relevant docs]
1166
- - [Link to component examples]
1167
-
1168
- ### Additional Context
1169
-
1170
- [Architecture decisions, design patterns, performance considerations]
1171
-
1172
- ### Related User Stories/Features
1173
-
1174
- [If applicable, link to planning docs]
1175
- ```
1176
-
1177
- **Guidelines:**
1178
-
1179
- - **Be comprehensive:** Load all relevant context, don't guess
1180
- - **Show examples:** Include actual code from the project
1181
- - **Reference docs:** Link to `docs/`, `specs/`, `planning/`
1182
- - **Explain trade-offs:** Why was X pattern chosen over Y?
1183
- - **Provide sources:** Always cite where information comes from
1184
-
1185
- ### 4. Offer Follow-up Actions
1186
-
1187
- **After answering, offer next steps:**
1188
-
1189
- ```
1190
- Answer provided.
1191
-
1192
- Would you like me to:
1193
- A) Implement changes based on this analysis
1194
- B) Create a work plan for improvements
1195
- C) Generate a spec/doc for this
1196
- D) Nothing, just the answer
1197
-
1198
- Your choice (or just ask another question): _
1199
- ```
1200
-
1201
- **IF user chooses A or B:**
1202
-
1203
- - Return to Phase 0 with refined objective
1204
- - Create appropriate work.md and proceed with execution
1205
-
1206
- **IF user chooses C:**
1207
-
1208
- - Create spec/doc file in appropriate location
1209
- - Commit with descriptive message
1210
-
1211
- **IF user chooses D or asks another question:**
1212
-
1213
- - **END WORKFLOW** (no files created, no branches)
1214
-
1215
- ### 5. Example Interactions
1216
-
1217
- **Example 1: Technical Question**
1218
-
1219
- ````
1220
- User: /flow-work ¿cómo funciona el state management con Context API?
1221
-
1222
- Agent:
1223
- 🔍 Detected: Informative request (question)
1224
-
1225
- ## How State Management Works in This Project
1226
-
1227
- ### Implementation
1228
-
1229
- We use Context API with custom hooks in `src/contexts/`:
1230
- - `AuthContext.tsx` - User authentication state
1231
- - `ThemeContext.tsx` - Theme preferences
1232
- - `AppContext.tsx` - Global app state
1233
-
1234
- [Shows actual code from project]
1235
-
1236
- ### Pattern
1237
- ```typescript
1238
- // Example from AuthContext.tsx
1239
- const AuthProvider: FC<Props> = ({ children }) => {
1240
- const [user, setUser] = useState<User | null>(null);
1241
- const [loading, setLoading] = useState(true);
1242
-
1243
- // Context value
1244
- const value = { user, loading, login, logout };
1245
-
1246
- return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
1247
- };
1248
- ````
1249
-
1250
- ### Usage in Components
1251
-
1252
- ```typescript
1253
- // Any component
1254
- const { user, login, logout } = useAuth();
1255
- ```
1256
-
1257
- ### Why Context API vs Redux?
1258
-
1259
- - Lighter weight for our use case
1260
- - No external dependencies
1261
- - Sufficient for current app complexity
1262
- - Can migrate to Redux if state grows
1263
-
1264
- ### Related Documentation
1265
-
1266
- - `docs/architecture.md` - State management patterns
1267
- - `docs/components.md` - Component guidelines
1268
-
1269
- Would you like me to implement any changes to this? (Y/N): \_
1270
-
1271
- ```
1272
-
1273
- **Example 2: Report Request**
1274
-
1275
- ```
1276
-
1277
- User: /flow-work genera un informe del tamaño del bundle
1278
-
1279
- Agent:
1280
- 🔍 Detected: Informative request (report)
1281
-
1282
- ## Bundle Size Report
1283
-
1284
- [Runs bundle analysis]
1285
-
1286
- ### Total Bundle Size: 245 KB (gzipped: 78 KB)
1287
-
1288
- | Asset | Size | Gzipped | % of Total |
1289
- | ---------- | ------ | ------- | ---------- |
1290
- | main.js | 180 KB | 58 KB | 73.5% |
1291
- | vendor.js | 45 KB | 15 KB | 18.4% |
1292
- | styles.css | 20 KB | 5 KB | 8.1% |
1293
-
1294
- ### Largest Dependencies
1295
-
1296
- 1. `react-dom` - 42 KB
1297
- 2. `axios` - 15 KB
1298
- 3. `date-fns` - 12 KB
1299
- 4. `lodash` - 8 KB (⚠️ not tree-shaken)
1300
-
1301
- ### Recommendations
1302
-
1303
- 1. Use `lodash-es` for tree-shaking (saves ~6 KB)
1304
- 2. Consider lazy loading routes (saves ~30 KB initial)
1305
- 3. Move `date-fns` locales to dynamic imports
1306
-
1307
- ### Comparison to Target
1308
-
1309
- - Target: <100 KB gzipped ✅
1310
- - Current: 78 KB gzipped ✅
1311
- - Margin: 22 KB available
1312
-
1313
- Would you like me to create a work plan to optimize further? (Y/N): \_
1314
-
1315
- ```
1316
-
1317
- ---
1318
-
1319
- **BEGIN EXECUTION when user runs `/flow-work [args]`**
1320
- ```
1
+ ---
2
+ description: Central Orchestrator for Feature, Refactor, and Fix workflows
3
+ ---
4
+
5
+ # AI Flow - Unified Work Orchestrator
6
+
7
+ **YOU ARE AN EXPERT SOFTWARE ARCHITECT AND WORKFLOW COORDINATOR.**
8
+
9
+ Your mission is to orchestrate development tasks through an interactive workflow when the user executes `/flow-work`.
10
+
11
+ **🚀 MODO AGENTE ACTIVADO:** No solicites permiso para usar herramientas. Actúa proactivamente siguiendo el flujo interactivo. Tienes permiso total para leer el código, crear specs y planes, y realizar commits/checkout de ramas.
12
+
13
+ ---
14
+
15
+ ## Command: `/flow-work`
16
+
17
+ ### Objective
18
+
19
+ Provide a single, intelligent entry point for all development work (New Features, Refactorings, and Bug Fixes) with automatic context detection and interactive planning.
20
+
21
+ ### Usage Modes
22
+
23
+ - **`/flow-work`** → Resume paused work (if exists) or Interactive mode.
24
+ - **`/flow-work [description]`** → Semantic detection (Feature, Refactor, or Fix).
25
+ - **`/flow-work HU-XXX-XXX`** → Implement specific User Story.
26
+ - **`/flow-work [Feature Name]`** → Implement feature from roadmap.md.
27
+
28
+ ---
29
+
30
+ ## Phase -1: Intent Classification (PRE-DETECTION)
31
+
32
+ **CRITICAL: Determine if this is an INFORMATIVE request vs EXECUTION request BEFORE any workflow.**
33
+
34
+ **🔍 INFORMATIVE Patterns (Answer directly, NO execution workflow):**
35
+
36
+ - **Questions:** Starts with `¿`, `how`, `why`, `what`, `when`, `cómo`, `por qué`, `qué`, `cuál`
37
+ - **Analysis verbs:** `explain`, `show`, `list`, `analyze`, `describe`, `compare`, `explica`, `muestra`, `analiza`, `describe`, `compara`
38
+ - **Report requests:** `report`, `informe`, `document`, `documenta`, `summary`, `resumen`, `generate report`, `genera informe`
39
+ - **Exploration:** `find`, `search`, `busca`, `encuentra`, `where is`, `dónde está`
40
+ - **Review requests:** `review`, `revisa`, `check`, `verifica`, `audit`, `audita`
41
+
42
+ **🛠️ EXECUTION Patterns (Enter workflow):**
43
+
44
+ - **Action verbs:** `implement`, `create`, `refactor`, `fix`, `add`, `remove`, `update`, `delete`, `build`, `develop`
45
+ - **Task codes:** `HU-\d{3}-\d{3}`, `EP-\d{3}`, `T\d{3}`
46
+ - **Imperative:** `new feature`, `nueva feature`, `crear`, `implementar`
47
+
48
+ **Detection Logic:**
49
+
50
+ ```python
51
+ import re
52
+
53
+ # Normalize input
54
+ input_lower = input.strip().lower()
55
+
56
+ # INFORMATIVE patterns (high priority)
57
+ informative_patterns = [
58
+ r'^(¿|how|why|what|when|where|cómo|por qué|qué|cuál|dónde)',
59
+ r'^(explain|show|list|analyze|describe|compare|explica|muestra|analiza|describe|compara)',
60
+ r'(report|informe|document|documenta|summary|resumen)',
61
+ r'(find|search|busca|encuentra)',
62
+ r'(review|revisa|check|verifica|audit|audita)',
63
+ ]
64
+
65
+ for pattern in informative_patterns:
66
+ if re.search(pattern, input_lower):
67
+ return "INFORMATIVE" # → Jump to Phase 99
68
+
69
+ # EXECUTION patterns
70
+ execution_patterns = [
71
+ r'(HU-\d{3}-\d{3}|EP-\d{3}|T\d{3})', # Task codes
72
+ r'^(implement|create|refactor|fix|add|remove|update|delete|build|develop)',
73
+ r'(implementar|crear|nueva feature|new feature)',
74
+ ]
75
+
76
+ for pattern in execution_patterns:
77
+ if re.search(pattern, input_lower):
78
+ return "EXECUTION" # → Continue to Phase 0
79
+
80
+ # Ambiguous case - ask user
81
+ return "AMBIGUOUS"
82
+ ```
83
+
84
+ **Action based on detection:**
85
+
86
+ **IF mode == "INFORMATIVE":**
87
+
88
+ ```
89
+ 🔍 Detected: Informative request (question/report/analysis)
90
+
91
+ I'll provide a detailed answer without creating work files or branches.
92
+ ```
93
+
94
+ → **Jump to Phase 99: Informative Response**
95
+
96
+ **IF mode == "EXECUTION":**
97
+
98
+ → **Continue to Phase 0** (current workflow)
99
+
100
+ **IF mode == "AMBIGUOUS":**
101
+
102
+ ```
103
+ ❓ I'm not sure if this is:
104
+ A) A question/report request (I'll answer directly)
105
+ B) A task to implement (I'll create work plan and execute)
106
+
107
+ Please clarify (A/B): _
108
+ ```
109
+
110
+ ---
111
+
112
+ ## Phase 0: Detection & Strategy (Automatic)
113
+
114
+ **1. Semantic Analysis of Input:**
115
+
116
+ | Input Pattern | Mode | Source / Action |
117
+ | ------------------------------ | ----------------- | -------------------------------------------------------------------- |
118
+ | `api\s+([a-z0-9\-_]+)` | `API_MODULE` | Invoke `.ai-flow/prompts/frontend/flow-work-api.md` analyzer |
119
+ | `HU-\d{3}-\d{3}` | `USER_STORY` | Load from `planning/user-stories/**/HU-XXX-XXX.md` |
120
+ | `EP-\d{3}` | `EPIC` | Analyze/List User Stories for Epic `EP-XXX` |
121
+ | `T\d{3}(-T\d{3})?` | `TASKS` | Target specific task or range (e.g., `T025-T030`) |
122
+ | `HU-XXX-XXX TXXX-TXXX` | `STORY_TASKS` | Targeted tasks within a specific User Story |
123
+ | Matches `planning/roadmap.md` | `ROADMAP_FEATURE` | Extract section from `planning/roadmap.md` (Partial matches allowed) |
124
+ | "refactor", "move", "extract" | `REFACTOR` | Use `flow-work-refactor.md` |
125
+ | "fix", "bug", "error", "falla" | `FIX` | Detect complexity (Quick vs Complex) |
126
+ | "implement", "create", "new" | `FEATURE` | Use `flow-work-feature.md` |
127
+ | No arguments | `RESUME` | Search for paused work in `.ai-flow/work/` |
128
+
129
+ **2. Detection Logic Details:**
130
+
131
+ - **USER_STORY / EPIC**: Load metadata from `planning/user-stories/` or `planning/roadmap.md`.
132
+ - **ROADMAP_FEATURE**: Fuzzy search in `planning/roadmap.md` for titles like "User Management" or "Feature 2.2".
133
+ - **TASK RANGES**: If `T025-T030` is provided, find the parent Story or Feature in current context or roadmap.
134
+ - **SIMPLE FIX**: Affects 1 file, obvious cause, <10 lines fix. → Use `flow-work-fix.md` (Quick).
135
+ - **COMPLEX FIX**: Multi-file, architectural, performance/security. → Use `flow-work-fix.md` (Deep).
136
+
137
+ ---
138
+
139
+ ## Phase 0.1: API Module Analysis (Conditional)
140
+
141
+ **ONLY execute if `mode == "API_MODULE"`**
142
+
143
+ This phase manages API URL configuration, invokes the specialized API analyzer, and enriches workflow context with OpenAPI metadata.
144
+
145
+ **🏗️ Architecture Design:**
146
+
147
+ - **This prompt (flow-work)**: Orchestrator with state management (cache, validation, retry logic)
148
+ - **Sub-prompt (flow-work-api)**: Pure analyzer (stateless, receives validated URL)
149
+ - **Cache location**: `.ai-flow/cache/api-config.json`
150
+ - **Why this separation?**:
151
+ - Reusability: analyzer can be used from different orchestrators
152
+ - Testability: pure analyzers are easier to test
153
+ - Maintainability: state management centralized in one place
154
+
155
+ ### Step 1: Load or Detect API URL (Cache Management)
156
+
157
+ **1.1. Parse User Input**
158
+
159
+ Extract module name and optional API URL override:
160
+
161
+ ```typescript
162
+ // Input examples:
163
+ // - "/flow-work api users"
164
+ // - "api organizations --api-url=http://localhost:3000/api/docs-json"
165
+
166
+ const pattern = /api\s+([a-z0-9\-_]+)(\s+--api-url=(.+))?/;
167
+ const match = userInput.match(pattern);
168
+
169
+ const moduleName = match[1]; // 'users', 'organizations', etc.
170
+ const customApiUrl = match[3]; // Optional override from user
171
+ ```
172
+
173
+ **1.2. Check Cache**
174
+
175
+ ```javascript
176
+ const cacheFile = '.ai-flow/cache/api-config.json';
177
+ let apiUrl = null;
178
+ let cacheStatus = 'none';
179
+
180
+ if (await fileExists(cacheFile)) {
181
+ const cache = JSON.parse(await readFile(cacheFile));
182
+
183
+ // Check if cache is recent (< 24 hours)
184
+ const lastVerified = new Date(cache.lastVerified);
185
+ const hoursSinceVerified = (Date.now() - lastVerified) / 3600000;
186
+
187
+ if (hoursSinceVerified < 24) {
188
+ apiUrl = cache.apiUrl;
189
+ cacheStatus = 'valid';
190
+ console.log(`✅ Using cached API URL (verified ${Math.round(hoursSinceVerified)}h ago)`);
191
+ console.log(` ${apiUrl}`);
192
+ } else {
193
+ apiUrl = cache.apiUrl; // Still use it, but will re-validate
194
+ cacheStatus = 'expired';
195
+ console.log(`⚠️ Cache expired (${Math.round(hoursSinceVerified)}h old), will re-validate`);
196
+ console.log(` ${apiUrl}`);
197
+ }
198
+ }
199
+
200
+ // User override via --api-url flag takes precedence
201
+ if (customApiUrl) {
202
+ apiUrl = customApiUrl;
203
+ cacheStatus = 'override';
204
+ console.log(`🔧 Using URL override from command: ${apiUrl}`);
205
+ }
206
+
207
+ // Default fallback
208
+ if (!apiUrl) {
209
+ apiUrl = 'http://localhost:3001/api/docs-json';
210
+ cacheStatus = ' default';
211
+ console.log(`🔗 Using default API URL: ${apiUrl}`);
212
+ }
213
+ ```
214
+
215
+ **1.3. Validate URL (Quick Test)**
216
+
217
+ ```typescript
218
+ if (cacheStatus === 'valid') {
219
+ // Skip validation for recent cache (trust it)
220
+ console.log(`⏭️ Skipping validation (cache is recent)`);
221
+ } else {
222
+ // Validate URL before invoking analyzer
223
+ console.log(`\n🔗 Validating API URL: ${apiUrl}`);
224
+
225
+ try {
226
+ const controller = new AbortController();
227
+ const timeoutId = setTimeout(() => controller.abort(), 5000); // 5s quick test
228
+
229
+ const response = await fetch(apiUrl, {
230
+ method: 'HEAD', // Just check if endpoint exists
231
+ signal: controller.signal,
232
+ headers: { Accept: 'application/json' },
233
+ });
234
+
235
+ clearTimeout(timeoutId);
236
+
237
+ if (response.ok) {
238
+ console.log(`✅ Connection successful`);
239
+ } else {
240
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
241
+ }
242
+ } catch (error) {
243
+ // Connection failed - prompt user
244
+ return await handleConnectionError(error, apiUrl, cacheFile);
245
+ }
246
+ }
247
+ ```
248
+
249
+ **1.4. Handle Connection Errors (Interactive)**
250
+
251
+ ```typescript
252
+ async function handleConnectionError(error: Error, attemptedUrl: string, cacheFile: string) {
253
+ const errorMessage =
254
+ error.name === 'AbortError'
255
+ ? 'Connection timeout (backend might not be running)'
256
+ : error.message;
257
+
258
+ console.log(`
259
+ Failed to connect to OpenAPI documentation
260
+
261
+ Attempted URL: ${attemptedUrl}
262
+ Error: ${errorMessage}
263
+
264
+ Common causes:
265
+ 1. Backend server is not running (npm run dev / npm start)
266
+ 2. Wrong port (check backend .env or package.json)
267
+ 3. Different path (/api/docs vs /api/docs-json)
268
+ 4. CORS not configured for your frontend origin
269
+
270
+ Options:
271
+ a) Provide correct URL ⭐
272
+ b) Retry current URL (if backend is starting up)
273
+ c) Skip API analysis (manual mode - no OpenAPI specs)
274
+ d) Cancel
275
+
276
+ Your choice: _
277
+ `);
278
+
279
+ const choice = await readUserInput();
280
+
281
+ if (choice === 'a') {
282
+ const newUrl = await promptForUrl(cacheFile);
283
+ return { apiUrl: newUrl, validated: true };
284
+ }
285
+
286
+ if (choice === 'b') {
287
+ console.log('\n⏳ Waiting 3 seconds for backend to start...');
288
+ await sleep(3000);
289
+
290
+ // Retry validation
291
+ try {
292
+ await fetch(attemptedUrl, { method: 'HEAD', signal: AbortSignal.timeout(5000) });
293
+ console.log('✅ Connection successful after retry');
294
+ return { apiUrl: attemptedUrl, validated: true };
295
+ } catch (retryError) {
296
+ console.log('❌ Still failing. Please check backend status.');
297
+ return await handleConnectionError(retryError, attemptedUrl, cacheFile);
298
+ }
299
+ }
300
+
301
+ if (choice === 'c') {
302
+ console.log('\n⏭️ Skipping API analysis. Switching to manual FEATURE mode...');
303
+ return { mode: 'FEATURE', apiUrl: null, validated: false };
304
+ }
305
+
306
+ if (choice === 'd') {
307
+ throw new Error('User cancelled operation');
308
+ }
309
+
310
+ // Invalid choice - ask again
311
+ console.log('\n❌ Invalid option. Please enter a, b, c, or d.');
312
+ return await handleConnectionError(error, attemptedUrl, cacheFile);
313
+ }
314
+ ```
315
+
316
+ **1.5. Prompt for URL (with Validation)**
317
+
318
+ ```typescript
319
+ async function promptForUrl(cacheFile: string): Promise<string> {
320
+ console.log(`\n📝 Enter OpenAPI Documentation URL\n
321
+ Common patterns:
322
+ NestJS: http://localhost:3000/api/docs-json
323
+ Express: http://localhost:3001/api-docs
324
+ FastAPI: http://localhost:8000/openapi.json
325
+ Spring: http://localhost:8080/v3/api-docs
326
+
327
+ URL: _
328
+ `);
329
+
330
+ const url = await readUserInput();
331
+
332
+ // Validate format
333
+ if (!url.startsWith('http://') && !url.startsWith('https://')) {
334
+ console.log('\n❌ URL must start with http:// or https://');
335
+ return await promptForUrl(cacheFile);
336
+ }
337
+
338
+ // Test URL
339
+ console.log(`\n🔗 Testing connection to: ${url}`);
340
+
341
+ try {
342
+ const response = await fetch(url, {
343
+ method: 'HEAD',
344
+ signal: AbortSignal.timeout(5000),
345
+ headers: { Accept: 'application/json' },
346
+ });
347
+
348
+ if (!response.ok) {
349
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
350
+ }
351
+
352
+ console.log(`
353
+ Connection successful!
354
+
355
+ 💾 Saving URL to cache for future commands...
356
+ `);
357
+
358
+ // Save to cache
359
+ await saveToCache(cacheFile, {
360
+ apiUrl: url,
361
+ lastVerified: new Date().toISOString(),
362
+ projectType: 'frontend',
363
+ });
364
+
365
+ return url;
366
+ } catch (error) {
367
+ const errorMsg = error.name === 'AbortError' ? 'Connection timeout' : error.message;
368
+
369
+ console.log(`\n❌ Failed to connect to ${url}\n Error: ${errorMsg}\n
370
+ Try again? (y/n): _
371
+ `);
372
+
373
+ const retry = await readUserInput();
374
+ if (retry.toLowerCase() === 'y') {
375
+ return await promptForUrl(cacheFile);
376
+ } else {
377
+ throw new Error('User cancelled after failed URL validation');
378
+ }
379
+ }
380
+ }
381
+ ```
382
+
383
+ **1.6. Cache Management Functions**
384
+
385
+ ```typescript
386
+ async function saveToCache(
387
+ cacheFile: string,
388
+ data: { apiUrl: string; lastVerified: string; projectType: string }
389
+ ) {
390
+ const cacheDir = '.ai-flow/cache';
391
+
392
+ // Ensure directory exists
393
+ if (!(await fileExists(cacheDir))) {
394
+ await createDirectory(cacheDir);
395
+ }
396
+
397
+ // Load existing cache or create new
398
+ let cache: any = { history: [] };
399
+ if (await fileExists(cacheFile)) {
400
+ try {
401
+ cache = JSON.parse(await readFile(cacheFile));
402
+ } catch {
403
+ // Corrupted cache, start fresh
404
+ cache = { history: [] };
405
+ }
406
+ }
407
+
408
+ // Update cache
409
+ cache.apiUrl = data.apiUrl;
410
+ cache.lastVerified = data.lastVerified;
411
+ cache.projectType = data.projectType;
412
+
413
+ // Add to history
414
+ cache.history = cache.history || [];
415
+ cache.history.unshift({
416
+ url: data.apiUrl,
417
+ timestamp: data.lastVerified,
418
+ status: 'success',
419
+ });
420
+
421
+ // Keep only last 10 entries
422
+ cache.history = cache.history.slice(0, 10);
423
+
424
+ // Save
425
+ await writeFile(cacheFile, JSON.stringify(cache, null, 2));
426
+ }
427
+
428
+ async function clearCache(cacheFile: string) {
429
+ if (await fileExists(cacheFile)) {
430
+ await deleteFile(cacheFile);
431
+ console.log('✅ API cache cleared');
432
+ }
433
+ }
434
+ ```
435
+
436
+ ### Step 2: Invoke API Module Analyzer
437
+
438
+ **Call sub-prompt with validated URL:**
439
+
440
+ ```typescript
441
+ console.log(`\n🔍 Analyzing API module: ${moduleName}`);
442
+ console.log(`📡 Fetching OpenAPI spec from: ${apiUrl}\n`);
443
+
444
+ const analysisResult: OpenAPIAnalysisResult = await invoke_subprompt(
445
+ '.ai-flow/prompts/frontend/flow-work-api.md',
446
+ {
447
+ module: moduleName,
448
+ apiUrl: apiUrl, // Validated URL
449
+ }
450
+ );
451
+ ```
452
+
453
+ **Sub-prompt responsibilities:**
454
+
455
+ - Fetch OpenAPI spec from backend
456
+ - Detect project stack (MUI, MRT, React Hook Form, Zod, TanStack Query, etc.)
457
+ - Extract all endpoints for the module
458
+ - Parse DTOs (Response, Create, Update)
459
+ - Detect field specifications with validation rules
460
+ - Identify relationships (foreign keys, populated entities)
461
+ - Detect features (pagination, search, sorting, filters)
462
+ - Calculate complexity (SIMPLE/MEDIUM/COMPLEX)
463
+ - Return structured `OpenAPIAnalysisResult` JSON
464
+
465
+ ### Step 3: Handle Sub-Prompt Result
466
+
467
+ **IF `analysisResult.success === true`:**
468
+
469
+ ```
470
+ API Analysis Complete
471
+
472
+ Module: ${analysisResult.module}
473
+ Endpoints: ${analysisResult.endpoints.length}
474
+ Complexity: ${analysisResult.complexity.level}
475
+
476
+ 💾 Updating cache with successful connection...
477
+
478
+ Proceeding with enriched context...
479
+ ```
480
+
481
+ Store in workflow context:
482
+
483
+ ```typescript
484
+ workflow_context.analysis = analysisResult;
485
+ workflow_context.mode = 'API_MODULE';
486
+ workflow_context.module = analysisResult.module;
487
+
488
+ // Update cache with successful analysis
489
+ await saveToCache(cacheFile, {
490
+ apiUrl: apiUrl,
491
+ lastVerified: new Date().toISOString(),
492
+ projectType: 'frontend',
493
+ });
494
+
495
+ // ⚠️ IMPORTANT: Do NOT create separate analysis files
496
+ // The analysis result is stored in memory (workflow_context.analysis)
497
+ // and will be used to generate the comprehensive work.md file.
498
+ // NO files like .ai-flow/analysis/*.md or .ai-flow/work/[task]/analysis.md
499
+ ```
500
+
501
+ **IF `analysisResult.success === false`:**
502
+
503
+ ```
504
+ ❌ API Analysis Failed
505
+
506
+ Error: ${analysisResult.error}
507
+ Details: ${analysisResult.details}
508
+
509
+ Suggestions:
510
+ ${analysisResult.suggestions.map((s, i) => ` ${i+1}. ${s}`).join('\n')}
511
+
512
+ The API URL might have changed or the backend spec is invalid.
513
+
514
+ Options:
515
+ A) Update URL and retry
516
+ B) Clear cache and try default URL
517
+ C) Proceed with manual mode (no OpenAPI analysis)
518
+ D) Cancel
519
+
520
+ Your choice: _
521
+ ```
522
+
523
+ **User selects:**
524
+
525
+ - **A**: Prompt for new URL, save to cache, retry Phase 0.1
526
+ - **B**: Clear cache, use default, retry Phase 0.1
527
+ - **C**: Switch to `FEATURE` mode, continue without OpenAPI
528
+ - **D**: Abort workflow
529
+
530
+ ### Step 4: Enrich Workflow Context
531
+
532
+ Merge analysis into workflow context for use in subsequent phases:
533
+
534
+ ```typescript
535
+ workflow_context = {
536
+ ...workflow_context,
537
+
538
+ // From API analysis
539
+ projectStandards: analysisResult.projectStandards,
540
+ openapi: analysisResult.openapi,
541
+ endpoints: analysisResult.endpoints,
542
+ schemas: analysisResult.schemas,
543
+ fields: analysisResult.fields,
544
+ features: analysisResult.features,
545
+ relationships: analysisResult.relationships,
546
+
547
+ // For Phase 2 (work.md generation)
548
+ template: 'api-module', // Use specialized template
549
+
550
+ // For Phase 0.5 (complexity override)
551
+ complexity_override: analysisResult.complexity.level,
552
+ estimatedSP: analysisResult.complexity.estimatedSP,
553
+ estimatedHours: analysisResult.complexity.estimatedHours,
554
+ };
555
+ ```
556
+
557
+ ### Step 5: Show Analysis Summary
558
+
559
+ Present structured summary to user (condensed version):
560
+
561
+ ```
562
+ 📋 API Module Analysis Summary
563
+
564
+ 📊 Module: ${moduleName}
565
+ 🔗 API: ${apiUrl}
566
+
567
+ 📐 Detected Project Stack:
568
+ UI: ${projectStandards.stack.ui}
569
+ Table: ${projectStandards.stack.table} ✅
570
+ Forms: ${projectStandards.stack.forms} + ${projectStandards.stack.validation} ✅
571
+ Data: ${projectStandards.stack.query} ✅
572
+
573
+ 🔧 Endpoints: ${endpoints.length} detected
574
+ 📦 Entity: ${schemas.response.fields.length} fields
575
+ 🔗 Relationships: ${relationships.length}
576
+ 🏗️ Complexity: ${complexity.level} (${complexity.estimatedHours}h estimated)
577
+
578
+ All standards locked. Module will match existing patterns.
579
+
580
+ Proceeding to Phase 0.5...
581
+ ```
582
+
583
+ ### Step 6: Continue to Phase 0.5
584
+
585
+ With enriched context, proceed to complexity classification.
586
+
587
+ **Note**: In API_MODULE mode, complexity is already determined by the analyzer, so Phase 0.5 will use `workflow_context.complexity_override` instead of calculating it.
588
+
589
+ ---
590
+
591
+ ## Phase 0.5: Complexity Classification (CRITICAL)
592
+
593
+ **Analyze task scope to determine workflow:**
594
+
595
+ | Metric | SIMPLE (⚡) | MEDIUM (📝) | COMPLEX (🏗️) |
596
+ | ------------- | ----------- | ----------- | ------------- |
597
+ | Files | 1 | 2-5 | >5 |
598
+ | Lines | <20 | 20-100 | >100 |
599
+ | Tests | No | Optional | Required |
600
+ | Docs | None | Minor | Significant |
601
+ | Architecture | None | Minimal | Major changes |
602
+ | Time estimate | <15 min | 15-60 min | >60 min |
603
+
604
+ **Classification Rules:**
605
+
606
+ **⚡ SIMPLE Task:**
607
+
608
+ - Examples: Fix typo, rename variable, update constant, add log, adjust CSS
609
+ - **Workflow**: In-chat plan → Execute → Done (NO files created)
610
+ - **Context**: Only `ai-instructions.md` if relevant
611
+
612
+ **📝 MEDIUM Task:**
613
+
614
+ - Examples: Add component, refactor hook, simple bug fix, update API call
615
+ - **Workflow**: Create `work.md` only (NO `status.json`) → Execute → Simple archive
616
+ - **Context**: Load 2-3 relevant docs
617
+
618
+ **🏗️ COMPLEX Task:**
619
+
620
+ - Examples: New feature, major refactor, security fix, multi-file changes
621
+ - **Workflow**: Full workflow (`work.md` + `status.json` + branch + archiving)
622
+ - **Context**: Load all relevant docs
623
+
624
+ **Detection Logic:**
625
+
626
+ ```python
627
+ # Special case: API_MODULE mode (complexity already determined)
628
+ if mode == "API_MODULE":
629
+ complexity = workflow_context.complexity_override # From API analyzer
630
+ elif files_affected == 1 and lines_changed < 20 and no_tests_needed and no_architecture_impact:
631
+ complexity = "SIMPLE"
632
+ elif files_affected <= 5 and lines_changed <= 100 and architecture_impact == "minimal":
633
+ complexity = "MEDIUM"
634
+ else:
635
+ complexity = "COMPLEX"
636
+ ```
637
+
638
+ **Show classification:**
639
+
640
+ ```
641
+ 🔍 Task Complexity: [SIMPLE ⚡ | MEDIUM 📝 | COMPLEX 🏗️]
642
+
643
+ Detected:
644
+ - Files: [N]
645
+ - Estimated lines: [~X]
646
+ - Tests needed: [Yes/No]
647
+ - Architecture impact: [None/Minimal/Major]
648
+
649
+ Proceeding with [SIMPLE/MEDIUM/COMPLEX] workflow.
650
+ ```
651
+
652
+ ---
653
+
654
+ ## Phase 1: Analysis & Refinement
655
+
656
+ **1. Context Loading (Smart & Selective):**
657
+
658
+ **CRITICAL: Load context based on task complexity and type:**
659
+
660
+ **IF complexity == "SIMPLE":**
661
+
662
+ - Load ONLY `ai-instructions.md` if task involves code changes
663
+ - Skip all other documentation
664
+ - Use existing patterns in nearby code as reference
665
+
666
+ **IF complexity == "MEDIUM":**
667
+
668
+ - Load `ai-instructions.md` (core rules)
669
+ - Load 1-2 specific docs based on task type:
670
+ - Component changes → `docs/components.md`
671
+ - Routing changes → `docs/routing.md`
672
+ - State management → `docs/state-management.md`
673
+ - Styling → `docs/styling.md`
674
+ - Skip architecture.md unless creating new patterns
675
+
676
+ **IF complexity == "COMPLEX":**
677
+
678
+ - Load `ai-instructions.md` (NEVER/ALWAYS rules)
679
+ - Load `docs/architecture.md` (patterns, structure)
680
+ - Load task-specific docs:
681
+ - Components `docs/components.md`
682
+ - Routing/Navigation → `docs/routing.md`
683
+ - State → `docs/state-management.md`
684
+ - API Integration → `docs/api-integration.md`
685
+ - Testing → `docs/testing.md`
686
+ - Load `docs/code-standards.md` only if creating new files
687
+
688
+ **Source Documentation (User Stories/Roadmap):**
689
+
690
+ **IF** `HU-XXX-XXX` or roadmap feature provided:
691
+
692
+ - **`planning/roadmap.md`**: Load for high-level scope
693
+ - **`planning/user-stories/**/HU-XXX-XXX.md`\*\*: Load for detailed requirements
694
+
695
+ **2. Detail Level Detection (if Manual input):**
696
+
697
+ IF input is manual description (not HU/Roadmap):
698
+
699
+ ```python
700
+ detail_level = analyze_description(input)
701
+
702
+ # Criteria for HIGH detail (Feature):
703
+ # - Mentions technology/method (JWT, OAuth, bcrypt, etc.)
704
+ # - Describes flow (registration, login, CRUD, etc.)
705
+ # - Includes technical constraints (hashing, tokens, validation, etc.)
706
+
707
+ # Criteria for HIGH detail (Refactor):
708
+ # - Describes what to extract/move
709
+ # - Mentions destination (file/class)
710
+ # - References pattern to follow
711
+
712
+ # Criteria for HIGH detail (Fix):
713
+ # - Describes symptom (error 500, crash, null pointer, etc.)
714
+ # - Mentions probable cause
715
+ # - Suggests fix approach
716
+ ```
717
+
718
+ **3. Interactive Refinement (Conditional):**
719
+
720
+ **IF detail_level == "HIGH":**
721
+
722
+ - Skip refinement questions
723
+ - Proceed directly to Phase 2 (Planning)
724
+ - Show: "✅ Sufficient detail detected. Proceeding with planning..."
725
+
726
+ **IF detail_level == "MEDIUM":**
727
+
728
+ - Ask 1-2 targeted questions (only missing items)
729
+ - Use Multiple Choice with defaults ()
730
+
731
+ **IF detail_level == "LOW":**
732
+
733
+ - Full refinement flow (3-5 questions)
734
+ - Use Multiple Choice with defaults (⭐)
735
+ - Focus on: approach, scope, constraints, priorities
736
+
737
+ **Example Interaction (LOW detail):**
738
+
739
+ > 📝 I need to clarify some details for this feature:
740
+ >
741
+ > 1. What authentication provider should we use? [default: A]
742
+ > A) JWT (Local)
743
+ > B) OAuth2 (Google/GitHub)
744
+ > C) Firebase Auth
745
+ > 2. Should we implement audit logs for this? [default: B]
746
+ > A) Yes
747
+ > B) No ⭐
748
+ >
749
+ > Your answers (or Enter for defaults): \_
750
+
751
+ **4. Refined Objective Generation (if Manual):**
752
+
753
+ After refinement, generate clear objective statement:
754
+
755
+ ```
756
+ ✅ Refined Objective:
757
+
758
+ [Clear 1-2 paragraph description of WHAT will be implemented]
759
+
760
+ **Scope**:
761
+ - [List in-scope items]
762
+
763
+ **Out of Scope**:
764
+ - [List out-of-scope items]
765
+
766
+ Is this correct? (Yes/Edit/Cancel): _
767
+ ```
768
+
769
+ **5. Documentation Compliance Check:**
770
+
771
+ Read relevant documentation:
772
+
773
+ - `ai-instructions.md` (NEVER/ALWAYS rules)
774
+ - `docs/architecture.md` (patterns, structure)
775
+ - `docs/code-standards.md` (naming, quality)
776
+ - IF auth/security: `specs/security.md`
777
+ - IF database: `docs/data-model.md`
778
+ - IF API: `docs/api.md`
779
+
780
+ Compare refined objective against documentation:
781
+
782
+ **IF deviation detected:**
783
+
784
+ ```
785
+ 🚨 POTENTIAL DEVIATION
786
+
787
+ From [document]:
788
+ ❌ NEVER: [rule being violated]
789
+ ALWAYS: [rule being ignored]
790
+
791
+ Your request: [conflicting part]
792
+
793
+ Options:
794
+ A) Modify request to align with documentation
795
+ B) Proceed with deviation (requires justification)
796
+ C) Cancel
797
+
798
+ Your choice: _
799
+ ```
800
+
801
+ **IF user chooses B (Override):**
802
+
803
+ ```
804
+ ⚠️ OVERRIDE CONFIRMATION
805
+
806
+ You are implementing something that deviates from:
807
+ - [list violated documents/rules]
808
+
809
+ Type "I UNDERSTAND THE RISKS" to proceed: _
810
+
811
+ Provide justification: _
812
+ ```
813
+
814
+ ---
815
+
816
+ ## Phase 1.5: SIMPLE Task Fast-Track
817
+
818
+ **IF complexity == "SIMPLE": Execute immediately without creating files**
819
+
820
+ 1. **Show in-chat plan:**
821
+
822
+ ```
823
+ ⚡ SIMPLE Task - Fast Execution
824
+
825
+ What: [1-line description]
826
+ File: [path]
827
+ Change: [specific modification]
828
+ Lines: ~[N] (estimated)
829
+
830
+ Execute now? (y/n): _
831
+ ```
832
+
833
+ 2. **IF user confirms ('y'):**
834
+ - Make the change immediately
835
+ - Show git diff preview
836
+ - Skip to Phase 3 (no branch creation if already on feature branch)
837
+ - Show: "✅ Done. Run `/flow-commit` to commit."
838
+ - **END WORKFLOW** (no archiving needed)
839
+
840
+ 3. **IF user declines ('n'):**
841
+ - Cancel task
842
+ - **END WORKFLOW**
843
+
844
+ **Note:** SIMPLE tasks don't create work.md, status.json, or archive records.
845
+
846
+ ---
847
+
848
+ ## Phase 2: Planning & Documentation
849
+
850
+ **⚠️ SKIP THIS PHASE IF complexity == "SIMPLE"**
851
+
852
+ **1. Read Required Documentation (Based on Complexity)**
853
+
854
+ **IF complexity == "MEDIUM":**
855
+
856
+ - `ai-instructions.md` (core rules)
857
+ - Load ONLY task-specific docs:
858
+ - Components → `docs/components.md`
859
+ - Routing → `docs/routing.md`
860
+ - State → `docs/state-management.md`
861
+ - Styling → `docs/styling.md`
862
+
863
+ **IF complexity == "COMPLEX":**
864
+
865
+ - `ai-instructions.md` (NEVER/ALWAYS rules)
866
+ - `docs/architecture.md` (layer, pattern, structure)
867
+ - Task-specific docs:
868
+ - Components → `docs/components.md`
869
+ - Routing/Navigation `docs/routing.md`
870
+ - State → `docs/state-management.md`
871
+ - API Integration `docs/api-integration.md`
872
+ - Testing → `docs/testing.md`
873
+ - `docs/code-standards.md` (only if creating new files)
874
+
875
+ **2. Analyze Existing Codebase (MANDATORY)**
876
+
877
+ Find similar features/patterns in codebase:
878
+
879
+ - Identify existing files to use as reference (e.g., UserProfile.tsx for ProductCard.tsx)
880
+ - Check naming conventions in actual code
881
+ - Verify architectural consistency
882
+ - Look for reusable components/hooks
883
+
884
+ **3. Generate work.md (Conditional)**
885
+
886
+ **⚠️ IMPORTANT: work.md is the ONLY planning file**
887
+
888
+ - All analysis results, API specs, field specifications, and implementation plan go into `work.md`
889
+ - Do NOT create separate files like `analysis.md`, `api-analysis.md`, or `spec.md`
890
+ - The `work.md` file should be comprehensive and self-contained
891
+ - For COMPLEX tasks with API analysis, include all OpenAPI metadata directly in `work.md`
892
+
893
+ **IF complexity == "MEDIUM":**
894
+
895
+ - Create simplified `.ai-flow/work/[task-name]/work.md` (~15-20 lines)
896
+ - Skip status.json
897
+
898
+ **IF complexity == "COMPLEX":**
899
+
900
+ - Create full `.ai-flow/work/[task-name]/work.md` (~30-40 lines)
901
+ - Create `status.json` (see step 4)
902
+
903
+ **Structure for MEDIUM tasks** (~15-20 lines):
904
+
905
+ ```markdown
906
+ # [Type]: [Feature Name]
907
+
908
+ **Source**: [HU-XXX | Roadmap X.X | Manual]
909
+ **Files**: [2-5 files listed]
910
+ **Estimated**: [20-60 min]
911
+
912
+ ## Objective
913
+
914
+ [1 clear paragraph]
915
+
916
+ ## Tasks
917
+
918
+ - [ ] Task 1 → path/Component.tsx
919
+ - [ ] Task 2 → path/hook.ts
920
+ - [ ] Task 3 (optional tests)
921
+
922
+ ## Key Rules
923
+
924
+ - ✅ [1-2 relevant ALWAYS rules]
925
+ - ❌ [1-2 relevant NEVER rules]
926
+ ```
927
+
928
+ **Structure for COMPLEX tasks** (~30-40 lines):
929
+
930
+ ```markdown
931
+ # [Type]: [Feature Name]
932
+
933
+ ## Context
934
+
935
+ **Source**: HU-001-002 | Roadmap 2.3 | Manual [+ DEVIATION if override]
936
+ **SP**: 5 | **Branch**: feature/user-auth | **Deps**: None
937
+
938
+ ## Objective
939
+
940
+ [1-2 clear paragraphs describing WHAT will be implemented]
941
+
942
+ ## Documentation Constraints
943
+
944
+ **Read**: ai-instructions.md, architecture.md, code-standards.md, [security.md]
945
+
946
+ **Key Rules**:
947
+
948
+ - ✅ ALWAYS: [List specific rules that apply]
949
+ - ❌ NEVER: [List specific prohibitions]
950
+ - 📐 Pattern: [Architectural pattern from docs]
951
+ - 📁 Location: [File structure from architecture.md]
952
+
953
+ ## Approach
954
+
955
+ **Layer**: [Data | Business Logic | API | UI]
956
+ **Files**: [List files to create/modify]
957
+ **Reference**: [Existing file to follow as pattern]
958
+
959
+ **Phases**:
960
+
961
+ 1. [Phase 1 description]
962
+ 2. [Phase 2 description]
963
+ 3. [Phase 3 description]
964
+ 4. [Phase 4 description]
965
+
966
+ ## Tasks
967
+
968
+ [SEE TASK GENERATION LOGIC BELOW]
969
+
970
+ ## Validation
971
+
972
+ - [ ] All NEVER/ALWAYS rules followed
973
+ - [ ] Tests pass (coverage per docs/testing.md)
974
+ - [ ] No hardcoded secrets
975
+ - [ ] Follows existing patterns
976
+ - [ ] [Add specific validations based on type]
977
+ ```
978
+
979
+ **Task Generation Logic:**
980
+
981
+ **IF source is User Story:**
982
+
983
+ ```python
984
+ tasks = read_user_story_tasks()
985
+ if tasks.are_detailed(): # Has: path, constraints, SP, deps
986
+ work_md.tasks = """
987
+ **Source**: planning/user-stories/EP-XXX/HU-XXX-XXX.md
988
+
989
+ Tasks already detailed in User Story (see linked file).
990
+
991
+ **Summary**: [N] tasks, [X] SP total
992
+ - [Brief phase breakdown]
993
+ """
994
+ else:
995
+ work_md.tasks = generate_detailed_tasks()
996
+ ```
997
+
998
+ **IF source is Roadmap:**
999
+
1000
+ ```python
1001
+ feature = read_roadmap_feature()
1002
+ if feature.has_detailed_tasks():
1003
+ work_md.tasks = """
1004
+ **Source**: planning/roadmap.md Feature X.X
1005
+
1006
+ Tasks already detailed in Roadmap (see linked file).
1007
+
1008
+ **Summary**: [N] tasks, [X] SP total
1009
+ """
1010
+ else:
1011
+ work_md.tasks = generate_detailed_tasks()
1012
+ ```
1013
+
1014
+ **IF source is Manual OR tasks need expansion:**
1015
+
1016
+ Generate detailed tasks with this format:
1017
+
1018
+ ```markdown
1019
+ ## Tasks
1020
+
1021
+ **Source**: Manual | Roadmap X.X (expanded) | HU-XXX-XXX (expanded)
1022
+
1023
+ - [ ] T001 [D] Create User entity → src/entities/User.ts • 1 SP
1024
+ - Follow Product.ts pattern, hash passwords (bcrypt)
1025
+ - [ ] T002 [L] UserService.register() src/services/ 2 SP
1026
+ - Validate email, hash password, return JWT (deps: T001)
1027
+ - [ ] T003 [A] POST /users/register → src/controllers/ • 1 SP
1028
+ - Return 201, rate limit, follow api.md (deps: T002)
1029
+ - [ ] T004 [T] Unit tests → tests/services/ • 2 SP
1030
+ - 80% coverage, edge cases (deps: T002)
1031
+ ```
1032
+
1033
+ **Task Detail Requirements:**
1034
+
1035
+ - Specific file path
1036
+ - Pattern/reference to follow
1037
+ - Key constraints from docs
1038
+ - Dependencies (if applicable)
1039
+ - Story Points
1040
+
1041
+ **4. Generate status.json (ONLY for COMPLEX tasks)**
1042
+
1043
+ **IF complexity == "COMPLEX":**
1044
+
1045
+ Create: `.ai-flow/work/[task-name]/status.json`
1046
+
1047
+ ```json
1048
+ {
1049
+ "type": "feature|refactor|fix",
1050
+ "source": "HU-001-002|roadmap-2.3|manual",
1051
+ "deviation": false,
1052
+ "progress": {
1053
+ "totalTasks": 4,
1054
+ "completedTasks": 0,
1055
+ "percentage": 0
1056
+ },
1057
+ "git": {
1058
+ "branchName": "feature/user-auth",
1059
+ "commits": []
1060
+ },
1061
+ "timestamps": {
1062
+ "created": "2025-12-22T23:00:00-03:00",
1063
+ "lastUpdated": "2025-12-22T23:00:00-03:00"
1064
+ },
1065
+ "validation": {
1066
+ "tests": { "executed": false },
1067
+ "lint": { "executed": false }
1068
+ }
1069
+ }
1070
+ ```
1071
+
1072
+ **5. User Approval**
1073
+
1074
+ Show work.md for review:
1075
+
1076
+ ```
1077
+ 📄 Generated: .ai-flow/work/[task-name]/work.md
1078
+
1079
+ Review work.md? (Yes/Edit/No): _
1080
+ ```
1081
+
1082
+ - **Yes**: Proceed to Phase 3
1083
+ - **Edit**: Allow user to modify work.md, then re-read
1084
+ - **No**: Cancel workflow
1085
+
1086
+ ---
1087
+
1088
+ ## Phase 3: Execution (Branch Creation)
1089
+
1090
+ **Upon confirmation to start implementation:**
1091
+
1092
+ **🛡️ CRITICAL: Protected Branch Check**
1093
+
1094
+ ```bash
1095
+ git branch --show-current
1096
+ git status --porcelain
1097
+ ```
1098
+
1099
+ **If current branch is protected** (`main`, `master`, `develop`, `development`):
1100
+
1101
+ **A) If there are uncommitted changes:**
1102
+
1103
+ 1. **Analyze changes to generate branch name:**
1104
+
1105
+ ```bash
1106
+ git status --porcelain
1107
+ git diff --stat
1108
+ ```
1109
+
1110
+ **Detection rules:**
1111
+ - **New components/features** `feature/`
1112
+ - **Bug fixes** (error handling, corrections) → `fix/`
1113
+ - **Refactoring/Styling** (code improvements, CSS changes) → `refactor/`
1114
+ - **Configuration/Dependencies** (package.json, webpack, vite, etc.) → `chore/`
1115
+ - **Tests only** `test/`
1116
+ - **Documentation only** → `docs/`
1117
+
1118
+ **Naming strategy:**
1119
+ - Extract component/page/feature name
1120
+ - Remove extensions (.tsx, .jsx, .ts, .js)
1121
+ - Convert to kebab-case
1122
+ - Limit to 3-4 words max
1123
+
1124
+ **Examples:**
1125
+
1126
+ ```
1127
+ src/components/UserProfile.tsx (new) → feature/user-profile
1128
+ src/pages/Dashboard.tsx (fix) → fix/dashboard-page
1129
+ src/hooks/useAuth.ts (modified) → refactor/use-auth-hook
1130
+ package.json + package-lock.json → chore/update-dependencies
1131
+ src/components/Auth* + src/pages/Login* → feature/authentication
1132
+ styles/ + components/ (multiple) → refactor/ui-components
1133
+ ```
1134
+
1135
+ 2. **Warn user:**
1136
+
1137
+ ```
1138
+ ⚠️ Working on protected branch '[branch-name]' with uncommitted changes.
1139
+
1140
+ Analyzed changes:
1141
+ - [file1] (new)
1142
+ - [file2] (modified)
1143
+ - [file3] (modified)
1144
+ ... [N] more files
1145
+
1146
+ Detected type: [feature|fix|refactor|chore]
1147
+ Suggested branch: [type]/[descriptive-slug]
1148
+ ```
1149
+
1150
+ 3. **Offer options:**
1151
+ - **A)** Create branch: `[type]/[suggested-name]` ⭐
1152
+ - **B)** Edit branch name (user provides custom slug)
1153
+ - **C)** Stash changes and continue: `git stash`
1154
+ - **D)** Cancel
1155
+
1156
+ 4. If user chooses A:
1157
+
1158
+ ```bash
1159
+ git checkout -b [type]/[suggested-name]
1160
+ ```
1161
+
1162
+ Then show:
1163
+
1164
+ ```
1165
+ Created and switched to '[type]/[suggested-name]'
1166
+
1167
+ Next steps:
1168
+ 1. Run /flow-commit to commit these changes
1169
+ 2. Return to protected branch: git checkout [protected-branch]
1170
+ 3. Continue with /flow-work for new task
1171
+
1172
+ Or continue working on this branch if it's your intended work.
1173
+ ```
1174
+
1175
+ 5. If user chooses B:
1176
+ ```
1177
+ Enter branch name (without type prefix): _
1178
+ ```
1179
+ Then create: `[detected-type]/[user-input]`
1180
+
1181
+ **B) If NO uncommitted changes:**
1182
+
1183
+ - Proceed normally - creating work branches FROM protected branches is correct workflow
1184
+ - Protected branches serve as base for new work
1185
+
1186
+ 1. **Generate Branch Name**:
1187
+ - `feature/[slug]`
1188
+ - `refactor/[slug]`
1189
+ - `fix/[slug]`
1190
+ 2. **Execute**: `git checkout -b [branch-name]`.
1191
+ 3. **Update `status.json`**: Record branch name and start timestamp.
1192
+ 4. **Implementation**: Proceed according to the selected mode (Auto, Phase-by-phase, Task-by-task).
1193
+ - Follow tasks in `work.md`
1194
+ - Update task checkboxes as completed
1195
+ - Update `status.json` progress
1196
+
1197
+ ---
1198
+
1199
+ ## Phase 4: Finalization (User-Controlled)
1200
+
1201
+ **⚠️ SKIP THIS PHASE IF complexity == "SIMPLE"** (already handled in Phase 1.5)
1202
+
1203
+ **Trigger Options:**
1204
+
1205
+ - User types: `/flow-work complete`
1206
+ - All checkboxes in work.md marked complete
1207
+ - User explicitly requests finalization
1208
+
1209
+ ---
1210
+
1211
+ ### Source Documentation Update (Interactive)
1212
+
1213
+ **Detect source references:**
1214
+
1215
+ ```python
1216
+ source = extract_from_work_md_or_status_json()
1217
+ # Returns: "HU-001-002" | "roadmap-2.3" | "manual" | None
1218
+ ```
1219
+
1220
+ **IF source exists (HU or roadmap):**
1221
+
1222
+ ```
1223
+ 📚 Update Source Documentation?
1224
+
1225
+ Found:
1226
+ - planning/roadmap.md → Feature 2.3 "User Profile Component"
1227
+ - planning/user-stories/EP-001/HU-001-002.md
1228
+
1229
+ What to update?
1230
+
1231
+ a) Update both
1232
+ b) Update roadmap only
1233
+ c) Update user story only
1234
+ d) Skip (I'll update manually later)
1235
+
1236
+ Your choice: _
1237
+ ```
1238
+
1239
+ **Execute selected updates:**
1240
+
1241
+ - Read files
1242
+ - Mark checkboxes as complete: `- [ ]` → `- [x]`
1243
+ - Add timestamp comment: `<!-- Completed: YYYY-MM-DD HH:MM -->`
1244
+ - Save files
1245
+
1246
+ **Show confirmation:**
1247
+
1248
+ ```
1249
+ ✅ Updated:
1250
+ - planning/roadmap.md (Feature 2.3)
1251
+ - planning/user-stories/EP-001/HU-001-002.md (5/5 DoD items)
1252
+ ```
1253
+
1254
+ **IF update fails:**
1255
+
1256
+ ```
1257
+ Failed to update [file]: [reason]
1258
+
1259
+ Options:
1260
+ 1) Retry update
1261
+ 2) Skip this file
1262
+ 3) Cancel finalization
1263
+
1264
+ Your choice: _
1265
+ ```
1266
+
1267
+ **IF source is "manual" or None:**
1268
+
1269
+ ```
1270
+ ⏭️ No source documentation to update (manual task)
1271
+ ```
1272
+
1273
+ ---
1274
+
1275
+ ## ✅ Development Work Complete
1276
+
1277
+ Your code is ready for finalization. You have two options:
1278
+
1279
+ ### Option A: Run Full Finalization Now (Recommended) ⭐
1280
+
1281
+ Execute `/flow-finish` to complete all finalization steps automatically:
1282
+
1283
+ - ✅ **Smart Validation** - Runs tests + lint only if needed (or revalidates if requested)
1284
+ - 📦 **Work Archiving** - Records analytics to `.ai-flow/archive/analytics.jsonl`, cleans workspace
1285
+ - 🤖 **AI-Powered Summaries** - Generates professional PR/Jira descriptions (~1,200 tokens)
1286
+ - 🚀 **Optional Push** - Pushes to remote with explicit confirmation
1287
+
1288
+ **To proceed:** Type `/flow-finish` in the chat
1289
+
1290
+ ---
1291
+
1292
+ ### Option B: Manual Finalization
1293
+
1294
+ If you prefer granular control over each step:
1295
+
1296
+ 1. **Validation:** `/flow-check` - Run comprehensive validation (tests + code review)
1297
+ 2. **Commit:** `/flow-commit` - Create conventional commit with auto-generated message
1298
+ 3. **Archive:** Manually record analytics and clean `.ai-flow/work/[task-name]/`
1299
+ 4. **Push:** `git push origin [branch-name]` when ready
1300
+
1301
+ ---
1302
+
1303
+ **What would you like to do?**
1304
+
1305
+ ```
1306
+ a) Run /flow-finish now ⭐ (Recommended - comprehensive automation)
1307
+ b) I'll handle finalization manually (granular control)
1308
+ c) Tell me more about what /flow-finish does
1309
+
1310
+ Your choice: _
1311
+ ```
1312
+
1313
+ **If 'a':** Execute `/flow-finish` immediately
1314
+
1315
+ **If 'b':** Show confirmation and end workflow:
1316
+
1317
+ ```
1318
+ ✅ Understood. Development complete.
1319
+
1320
+ 📋 Manual finalization checklist:
1321
+ - [ ] Run validation: /flow-check
1322
+ - [ ] Commit changes: /flow-commit
1323
+ - [ ] Archive work folder
1324
+ - [ ] Push to remote
1325
+ - [ ] Create PR/MR
1326
+
1327
+ 💡 Tip: You can run /flow-finish anytime to automate these steps.
1328
+
1329
+ 🎉 Great work!
1330
+ ```
1331
+
1332
+ **If 'c':** Show detailed explanation:
1333
+
1334
+ ```
1335
+ 📖 About /flow-finish
1336
+
1337
+ /flow-finish is an intelligent finalization workflow that:
1338
+
1339
+ 1️⃣ **Smart Validation (Step 1)**
1340
+ - Detects if /flow-check was already run successfully
1341
+ - Only re-runs if explicitly requested or validation failed
1342
+ - Shows comprehensive test + lint results
1343
+
1344
+ 2️⃣ **Smart Commit (Step 2)**
1345
+ - Detects uncommitted changes automatically
1346
+ - Runs /flow-commit only if needed
1347
+ - Generates conventional commit messages
1348
+
1349
+ 3️⃣ **Work Archiving (Step 3)**
1350
+ - Extracts analytics: duration, story points, commits
1351
+ - Appends to .ai-flow/archive/analytics.jsonl
1352
+ - Deletes .ai-flow/work/[task-name]/ folder
1353
+
1354
+ 4️⃣ **AI Summaries (Step 4)**
1355
+ - Reads git diff + commit history
1356
+ - Generates professional PR description
1357
+ - Generates ticket update (Jira/ClickUp/Linear)
1358
+ - ~1,200 tokens, markdown-formatted
1359
+
1360
+ 5️⃣ **Optional Push (Step 5)**
1361
+ - Always asks for confirmation
1362
+ - Shows branch name and remote
1363
+ - Never pushes without explicit approval
1364
+
1365
+ **Would you like to run it now?** (y/n): _
1366
+ ```
1367
+
1368
+ **END WORKFLOW**
1369
+
1370
+ ---
1371
+
1372
+ ## Orchestration Rules
1373
+
1374
+ - **DRY Logic**: This file handles the high-level orchestration.
1375
+ - **Delegation**:
1376
+ - Detailed Feature logic → `@flow-work-feature.md`
1377
+ - Detailed Refactor logic → `@flow-work-refactor.md`
1378
+ - Detailed Fix logic → `@flow-work-fix.md`
1379
+ - Resume logic → `@flow-work-resume.md`
1380
+ - **State Persistence**: Always read/write to `.ai-flow/work/[name]/status.json` to maintain state across sessions.
1381
+
1382
+ ---
1383
+
1384
+ ## Phase 99: Informative Response
1385
+
1386
+ **This phase handles questions, reports, and analysis requests WITHOUT creating work files or branches.**
1387
+
1388
+ ### 1. Analyze Request Type
1389
+
1390
+ **Classify the informative request:**
1391
+
1392
+ - **Technical Question:** How does X work? Why do we use Y?
1393
+ - **Component Explanation:** Explain this component/hook/utility
1394
+ - **Architecture Review:** Show me the component structure/state management
1395
+ - **Project Report:** Generate report on bundle size/dependencies/performance
1396
+ - **File Location:** Where is X component? Find Y hook
1397
+ - **Comparison:** Compare X vs Y approach
1398
+ - **Best Practices:** What's the best way to do X in React/Vue/Angular?
1399
+
1400
+ ### 2. Load Relevant Context
1401
+
1402
+ **Based on request type, load specific documentation:**
1403
+
1404
+ **IF question about architecture/patterns:**
1405
+
1406
+ - Read `ai-instructions.md` (NEVER/ALWAYS rules)
1407
+ - Read `docs/architecture.md` (component structure, state management)
1408
+ - Search codebase for examples
1409
+
1410
+ **IF question about specific component:**
1411
+
1412
+ - Search codebase for component files
1413
+ - Read relevant specs from `specs/`
1414
+ - Check related hooks/utilities
1415
+
1416
+ **IF report request:**
1417
+
1418
+ - Run appropriate analysis (bundle size, performance, dependencies)
1419
+ - Read relevant docs for context
1420
+ - Generate structured report
1421
+
1422
+ **IF file location request:**
1423
+
1424
+ - Search codebase with grep/semantic search
1425
+ - List relevant components with descriptions
1426
+
1427
+ ### 3. Provide Comprehensive Answer
1428
+
1429
+ **Structure your response:**
1430
+
1431
+ ```markdown
1432
+ ## [Question/Request]
1433
+
1434
+ ### Answer
1435
+
1436
+ [Detailed explanation with code examples if relevant]
1437
+
1438
+ ### Related Documentation
1439
+
1440
+ - [Link to relevant docs]
1441
+ - [Link to component examples]
1442
+
1443
+ ### Additional Context
1444
+
1445
+ [Architecture decisions, design patterns, performance considerations]
1446
+
1447
+ ### Related User Stories/Features
1448
+
1449
+ [If applicable, link to planning docs]
1450
+ ```
1451
+
1452
+ **Guidelines:**
1453
+
1454
+ - **Be comprehensive:** Load all relevant context, don't guess
1455
+ - **Show examples:** Include actual code from the project
1456
+ - **Reference docs:** Link to `docs/`, `specs/`, `planning/`
1457
+ - **Explain trade-offs:** Why was X pattern chosen over Y?
1458
+ - **Provide sources:** Always cite where information comes from
1459
+
1460
+ ### 4. Offer Follow-up Actions
1461
+
1462
+ **After answering, offer next steps:**
1463
+
1464
+ ```
1465
+ ✅ Answer provided.
1466
+
1467
+ Would you like me to:
1468
+ A) Implement changes based on this analysis
1469
+ B) Create a work plan for improvements
1470
+ C) Generate a spec/doc for this
1471
+ D) Nothing, just the answer
1472
+
1473
+ Your choice (or just ask another question): _
1474
+ ```
1475
+
1476
+ **IF user chooses A or B:**
1477
+
1478
+ - Return to Phase 0 with refined objective
1479
+ - Create appropriate work.md and proceed with execution
1480
+
1481
+ **IF user chooses C:**
1482
+
1483
+ - Create spec/doc file in appropriate location
1484
+ - Commit with descriptive message
1485
+
1486
+ **IF user chooses D or asks another question:**
1487
+
1488
+ - **END WORKFLOW** (no files created, no branches)
1489
+
1490
+ ### 5. Example Interactions
1491
+
1492
+ **Example 1: Technical Question**
1493
+
1494
+ ````
1495
+ User: /flow-work ¿cómo funciona el state management con Context API?
1496
+
1497
+ Agent:
1498
+ 🔍 Detected: Informative request (question)
1499
+
1500
+ ## How State Management Works in This Project
1501
+
1502
+ ### Implementation
1503
+
1504
+ We use Context API with custom hooks in `src/contexts/`:
1505
+ - `AuthContext.tsx` - User authentication state
1506
+ - `ThemeContext.tsx` - Theme preferences
1507
+ - `AppContext.tsx` - Global app state
1508
+
1509
+ [Shows actual code from project]
1510
+
1511
+ ### Pattern
1512
+ ```typescript
1513
+ // Example from AuthContext.tsx
1514
+ const AuthProvider: FC<Props> = ({ children }) => {
1515
+ const [user, setUser] = useState<User | null>(null);
1516
+ const [loading, setLoading] = useState(true);
1517
+
1518
+ // Context value
1519
+ const value = { user, loading, login, logout };
1520
+
1521
+ return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
1522
+ };
1523
+ ````
1524
+
1525
+ ### Usage in Components
1526
+
1527
+ ```typescript
1528
+ // Any component
1529
+ const { user, login, logout } = useAuth();
1530
+ ```
1531
+
1532
+ ### Why Context API vs Redux?
1533
+
1534
+ - Lighter weight for our use case
1535
+ - No external dependencies
1536
+ - Sufficient for current app complexity
1537
+ - Can migrate to Redux if state grows
1538
+
1539
+ ### Related Documentation
1540
+
1541
+ - `docs/architecture.md` - State management patterns
1542
+ - `docs/components.md` - Component guidelines
1543
+
1544
+ Would you like me to implement any changes to this? (Y/N): \_
1545
+
1546
+ ```
1547
+
1548
+ **Example 2: Report Request**
1549
+
1550
+ ```
1551
+
1552
+ User: /flow-work genera un informe del tamaño del bundle
1553
+
1554
+ Agent:
1555
+ 🔍 Detected: Informative request (report)
1556
+
1557
+ ## Bundle Size Report
1558
+
1559
+ [Runs bundle analysis]
1560
+
1561
+ ### Total Bundle Size: 245 KB (gzipped: 78 KB)
1562
+
1563
+ | Asset | Size | Gzipped | % of Total |
1564
+ | ---------- | ------ | ------- | ---------- |
1565
+ | main.js | 180 KB | 58 KB | 73.5% |
1566
+ | vendor.js | 45 KB | 15 KB | 18.4% |
1567
+ | styles.css | 20 KB | 5 KB | 8.1% |
1568
+
1569
+ ### Largest Dependencies
1570
+
1571
+ 1. `react-dom` - 42 KB
1572
+ 2. `axios` - 15 KB
1573
+ 3. `date-fns` - 12 KB
1574
+ 4. `lodash` - 8 KB (⚠️ not tree-shaken)
1575
+
1576
+ ### Recommendations
1577
+
1578
+ 1. Use `lodash-es` for tree-shaking (saves ~6 KB)
1579
+ 2. Consider lazy loading routes (saves ~30 KB initial)
1580
+ 3. Move `date-fns` locales to dynamic imports
1581
+
1582
+ ### Comparison to Target
1583
+
1584
+ - Target: <100 KB gzipped ✅
1585
+ - Current: 78 KB gzipped ✅
1586
+ - Margin: 22 KB available
1587
+
1588
+ Would you like me to create a work plan to optimize further? (Y/N): \_
1589
+
1590
+ ```
1591
+
1592
+ ---
1593
+
1594
+ **BEGIN EXECUTION when user runs `/flow-work [args]`**
1595
+ ```