ai-flow-dev 2.7.0 → 2.8.0

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 +725 -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 +725 -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 +910 -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 +725 -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 +910 -0
  70. package/prompts/frontend/flow-release.md +519 -0
  71. package/prompts/frontend/flow-work-api.md +1540 -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 +1583 -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 +725 -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 +910 -0
  95. package/prompts/mobile/flow-release.md +751 -0
  96. package/prompts/mobile/flow-work-api.md +1493 -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 +1593 -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 +47 -47
@@ -1,1329 +1,1593 @@
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 styling
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 screen
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-screen 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
- - UI changes → `docs/components.md`
215
- - Navigation `docs/navigation.md`
216
- - Security → `specs/security.md`
217
- - Skip architecture.md unless creating new patterns
218
-
219
- **IF complexity == "COMPLEX":**
220
-
221
- - Load `ai-instructions.md` (NEVER/ALWAYS rules)
222
- - Load `docs/architecture.md` (patterns, structure)
223
- - Load task-specific docs:
224
- - UI → `docs/components.md`
225
- - Security/Auth → `specs/security.md`
226
- - Navigation `docs/navigation.md`
227
- - Tests `docs/testing.md`
228
- - Load `docs/code-standards.md` only if creating new files
229
-
230
- **Source Documentation (User Stories/Roadmap):**
231
-
232
- **IF** `HU-XXX-XXX` or roadmap feature provided:
233
-
234
- - **`planning/roadmap.md`**: Load for high-level scope
235
- - **`planning/user-stories/**/HU-XXX-XXX.md`\*\*: Load for detailed requirements
236
-
237
- **2. Detail Level Detection (if Manual input):**
238
-
239
- IF input is manual description (not HU/Roadmap):
240
-
241
- ```python
242
- detail_level = analyze_description(input)
243
-
244
- # Criteria for HIGH detail (Feature):
245
- # - Mentions technology/method (JWT, OAuth, bcrypt, etc.)
246
- # - Describes flow (registration, login, CRUD, etc.)
247
- # - Includes technical constraints (hashing, tokens, validation, etc.)
248
-
249
- # Criteria for HIGH detail (Refactor):
250
- # - Describes what to extract/move
251
- # - Mentions destination (file/class)
252
- # - References pattern to follow
253
-
254
- # Criteria for HIGH detail (Fix):
255
- # - Describes symptom (error 500, crash, null pointer, etc.)
256
- # - Mentions probable cause
257
- # - Suggests fix approach
258
- ```
259
-
260
- **3. Interactive Refinement (Conditional):**
261
-
262
- **IF detail_level == "HIGH":**
263
-
264
- - Skip refinement questions
265
- - Proceed directly to Phase 2 (Planning)
266
- - Show: "✅ Sufficient detail detected. Proceeding with planning..."
267
-
268
- **IF detail_level == "MEDIUM":**
269
-
270
- - Ask 1-2 targeted questions (only missing items)
271
- - Use Multiple Choice with defaults ()
272
-
273
- **IF detail_level == "LOW":**
274
-
275
- - Full refinement flow (3-5 questions)
276
- - Use Multiple Choice with defaults (⭐)
277
- - Focus on: approach, scope, constraints, priorities
278
-
279
- **Example Interaction (LOW detail):**
280
-
281
- > 📝 I need to clarify some details for this feature:
282
- >
283
- > 1. What authentication provider should we use? [default: A]
284
- > A) JWT (Local) ⭐
285
- > B) OAuth2 (Google/GitHub)
286
- > C) Firebase Auth
287
- > 2. Should we implement audit logs for this? [default: B]
288
- > A) Yes
289
- > B) No ⭐
290
- >
291
- > Your answers (or Enter for defaults): \_
292
-
293
- **4. Refined Objective Generation (if Manual):**
294
-
295
- After refinement, generate clear objective statement:
296
-
297
- ```
298
- ✅ Refined Objective:
299
-
300
- [Clear 1-2 paragraph description of WHAT will be implemented]
301
-
302
- **Scope**:
303
- - [List in-scope items]
304
-
305
- **Out of Scope**:
306
- - [List out-of-scope items]
307
-
308
- Is this correct? (Yes/Edit/Cancel): _
309
- ```
310
-
311
- **5. Documentation Compliance Check:**
312
-
313
- Read relevant documentation:
314
-
315
- - `ai-instructions.md` (NEVER/ALWAYS rules)
316
- - `docs/architecture.md` (patterns, structure)
317
- - `docs/code-standards.md` (naming, quality)
318
- - IF auth/security: `specs/security.md`
319
- - IF database: `docs/data-model.md`
320
- - IF API: `docs/api.md`
321
-
322
- Compare refined objective against documentation:
323
-
324
- **IF deviation detected:**
325
-
326
- ```
327
- 🚨 POTENTIAL DEVIATION
328
-
329
- From [document]:
330
- NEVER: [rule being violated]
331
- ✅ ALWAYS: [rule being ignored]
332
-
333
- Your request: [conflicting part]
334
-
335
- Options:
336
- A) Modify request to align with documentation
337
- B) Proceed with deviation (requires justification)
338
- C) Cancel
339
-
340
- Your choice: _
341
- ```
342
-
343
- **IF user chooses B (Override):**
344
-
345
- ```
346
- ⚠️ OVERRIDE CONFIRMATION
347
-
348
- You are implementing something that deviates from:
349
- - [list violated documents/rules]
350
-
351
- Type "I UNDERSTAND THE RISKS" to proceed: _
352
-
353
- Provide justification: _
354
- ```
355
-
356
- ---
357
-
358
- ## Phase 1.5: SIMPLE Task Fast-Track
359
-
360
- **IF complexity == "SIMPLE": Execute immediately without creating files**
361
-
362
- 1. **Show in-chat plan:**
363
-
364
- ```
365
- SIMPLE Task - Fast Execution
366
-
367
- What: [1-line description]
368
- File: [path]
369
- Change: [specific modification]
370
- Lines: ~[N] (estimated)
371
-
372
- Execute now? (y/n): _
373
- ```
374
-
375
- 2. **IF user confirms ('y'):**
376
- - Make the change immediately
377
- - Show git diff preview
378
- - Skip to Phase 3 (no branch creation if already on feature branch)
379
- - Show: "✅ Done. Run `/flow-commit` to commit."
380
- - **END WORKFLOW** (no archiving needed)
381
-
382
- 3. **IF user declines ('n'):**
383
- - Cancel task
384
- - **END WORKFLOW**
385
-
386
- **Note:** SIMPLE tasks don't create work.md, status.json, or archive records.
387
-
388
- ---
389
-
390
- ## Phase 2: Planning & Documentation
391
-
392
- **⚠️ SKIP THIS PHASE IF complexity == "SIMPLE"**
393
-
394
- **1. Read Required Documentation (Based on Complexity)**
395
-
396
- **IF complexity == "MEDIUM":**
397
-
398
- - `ai-instructions.md` (core rules)
399
- - Load ONLY task-specific docs:
400
- - UI → `docs/components.md`
401
- - Navigation `docs/navigation.md`
402
- - Security → `specs/security.md`
403
-
404
- **IF complexity == "COMPLEX":**
405
-
406
- - `ai-instructions.md` (NEVER/ALWAYS rules)
407
- - `docs/architecture.md` (layer, pattern, structure)
408
- - Task-specific docs:
409
- - UI → `docs/components.md`
410
- - Security/Auth → `specs/security.md`
411
- - Navigation → `docs/navigation.md`
412
- - Tests → `docs/testing.md`
413
- - `docs/code-standards.md` (only if creating new files)
414
-
415
- **2. Analyze Existing Codebase (MANDATORY)**
416
-
417
- Find similar features/patterns in codebase:
418
-
419
- - Identify existing files to use as reference (e.g., ProfileScreen.tsx for SettingsScreen.tsx)
420
- - Check naming conventions in actual code
421
- - Verify architectural consistency
422
- - Look for reusable components/hooks
423
-
424
- **3. Generate work.md (Conditional)**
425
-
426
- **IF complexity == "MEDIUM":**
427
-
428
- - Create simplified `.ai-flow/work/[task-name]/work.md` (~15-20 lines)
429
- - Skip status.json
430
-
431
- **IF complexity == "COMPLEX":**
432
-
433
- - Create full `.ai-flow/work/[task-name]/work.md` (~30-40 lines)
434
- - Create `status.json` (see step 4)
435
-
436
- **Structure for MEDIUM tasks** (~15-20 lines):
437
-
438
- ```markdown
439
- # [Type]: [Feature Name]
440
-
441
- **Source**: [HU-XXX | Roadmap X.X | Manual]
442
- **Files**: [2-5 files listed]
443
- **Estimated**: [20-60 min]
444
-
445
- ## Objective
446
-
447
- [1 clear paragraph]
448
-
449
- ## Tasks
450
-
451
- - [ ] Task 1 → path/file.tsx
452
- - [ ] Task 2 → path/file.ts
453
- - [ ] Task 3 (optional tests)
454
-
455
- ## Key Rules
456
-
457
- - [1-2 relevant ALWAYS rules]
458
- - [1-2 relevant NEVER rules]
459
- ```
460
-
461
- **Structure for COMPLEX tasks** (~30-40 lines):
462
-
463
- ```markdown
464
- # [Type]: [Feature Name]
465
-
466
- ## Context
467
-
468
- **Source**: HU-001-002 | Roadmap 2.3 | Manual [+ DEVIATION if override]
469
- **SP**: 5 | **Branch**: feature/user-auth | **Deps**: None
470
-
471
- ## Objective
472
-
473
- [1-2 clear paragraphs describing WHAT will be implemented]
474
-
475
- ## Documentation Constraints
476
-
477
- **Read**: ai-instructions.md, architecture.md, code-standards.md, [security.md]
478
-
479
- **Key Rules**:
480
-
481
- - ALWAYS: [List specific rules that apply]
482
- - ❌ NEVER: [List specific prohibitions]
483
- - 📐 Pattern: [Architectural pattern from docs]
484
- - 📁 Location: [File structure from architecture.md]
485
-
486
- ## Approach
487
-
488
- **Layer**: [Data | Business Logic | API | UI]
489
- **Files**: [List files to create/modify]
490
- **Reference**: [Existing file to follow as pattern]
491
-
492
- **Phases**:
493
-
494
- 1. [Phase 1 description]
495
- 2. [Phase 2 description]
496
- 3. [Phase 3 description]
497
- 4. [Phase 4 description]
498
-
499
- ## Tasks
500
-
501
- [SEE TASK GENERATION LOGIC BELOW]
502
-
503
- ## Validation
504
-
505
- - [ ] All NEVER/ALWAYS rules followed
506
- - [ ] Tests pass (coverage per docs/testing.md)
507
- - [ ] No hardcoded secrets
508
- - [ ] Follows existing patterns
509
- - [ ] [Add specific validations based on type]
510
- ```
511
-
512
- **Task Generation Logic:**
513
-
514
- **IF source is User Story:**
515
-
516
- ```python
517
- tasks = read_user_story_tasks()
518
- if tasks.are_detailed(): # Has: path, constraints, SP, deps
519
- work_md.tasks = """
520
- **Source**: planning/user-stories/EP-XXX/HU-XXX-XXX.md
521
-
522
- Tasks already detailed in User Story (see linked file).
523
-
524
- **Summary**: [N] tasks, [X] SP total
525
- - [Brief phase breakdown]
526
- """
527
- else:
528
- work_md.tasks = generate_detailed_tasks()
529
- ```
530
-
531
- **IF source is Roadmap:**
532
-
533
- ```python
534
- feature = read_roadmap_feature()
535
- if feature.has_detailed_tasks():
536
- work_md.tasks = """
537
- **Source**: planning/roadmap.md Feature X.X
538
-
539
- Tasks already detailed in Roadmap (see linked file).
540
-
541
- **Summary**: [N] tasks, [X] SP total
542
- """
543
- else:
544
- work_md.tasks = generate_detailed_tasks()
545
- ```
546
-
547
- **IF source is Manual OR tasks need expansion:**
548
-
549
- Generate detailed tasks with this format:
550
-
551
- ```markdown
552
- ## Tasks
553
-
554
- **Source**: Manual | Roadmap X.X (expanded) | HU-XXX-XXX (expanded)
555
-
556
- - [ ] T001 [D] Create User entity → src/entities/User.ts • 1 SP
557
- - Follow Product.ts pattern, hash passwords (bcrypt)
558
- - [ ] T002 [L] UserService.register() → src/services/ • 2 SP
559
- - Validate email, hash password, return JWT (deps: T001)
560
- - [ ] T003 [A] POST /users/register → src/controllers/ • 1 SP
561
- - Return 201, rate limit, follow api.md (deps: T002)
562
- - [ ] T004 [T] Unit tests → tests/services/ • 2 SP
563
- - 80% coverage, edge cases (deps: T002)
564
- ```
565
-
566
- **Task Detail Requirements:**
567
-
568
- - Specific file path
569
- - Pattern/reference to follow
570
- - Key constraints from docs
571
- - Dependencies (if applicable)
572
- - Story Points
573
-
574
- **4. Generate status.json (ONLY for COMPLEX tasks)**
575
-
576
- **IF complexity == "COMPLEX":**
577
-
578
- Create: `.ai-flow/work/[task-name]/status.json`
579
-
580
- ```json
581
- {
582
- "type": "feature|refactor|fix",
583
- "source": "HU-001-002|roadmap-2.3|manual",
584
- "deviation": false,
585
- "progress": {
586
- "totalTasks": 4,
587
- "completedTasks": 0,
588
- "percentage": 0
589
- },
590
- "git": {
591
- "branchName": "feature/user-auth",
592
- "commits": []
593
- },
594
- "timestamps": {
595
- "created": "2025-12-22T23:00:00-03:00",
596
- "lastUpdated": "2025-12-22T23:00:00-03:00"
597
- },
598
- "validation": {
599
- "tests": { "executed": false },
600
- "lint": { "executed": false }
601
- }
602
- }
603
- ```
604
-
605
- **5. User Approval**
606
-
607
- Show work.md for review:
608
-
609
- ```
610
- 📄 Generated: .ai-flow/work/[task-name]/work.md
611
-
612
- Review work.md? (Yes/Edit/No): _
613
- ```
614
-
615
- - **Yes**: Proceed to Phase 3
616
- - **Edit**: Allow user to modify work.md, then re-read
617
- - **No**: Cancel workflow
618
-
619
- ---
620
-
621
- ## Phase 3: Execution (Branch Creation)
622
-
623
- **Upon confirmation to start implementation:**
624
-
625
- **🛡️ CRITICAL: Protected Branch Check**
626
-
627
- ```bash
628
- git branch --show-current
629
- git status --porcelain
630
- ```
631
-
632
- **If current branch is protected** (`main`, `master`, `develop`, `development`):
633
-
634
- **A) If there are uncommitted changes:**
635
-
636
- 1. **Analyze changes to generate branch name:**
637
-
638
- ```bash
639
- git status --porcelain
640
- git diff --stat
641
- ```
642
-
643
- **Detection rules:**
644
- - **New screens/features** → `feature/`
645
- - **Bug fixes** (crash fixes, error handling) → `fix/`
646
- - **Refactoring/Optimization** (code improvements, performance) → `refactor/`
647
- - **Native configs** (android/, ios/, dependencies) → `chore/`
648
- - **Tests only** → `test/`
649
- - **Documentation only** → `docs/`
650
-
651
- **Naming strategy:**
652
- - Extract screen/module/feature name
653
- - Remove extensions (.tsx, .ts, .js)
654
- - Convert to kebab-case
655
- - Limit to 3-4 words max
656
-
657
- **Examples:**
658
-
659
- ```
660
- src/screens/ProfileScreen.tsx (new) → feature/profile-screen
661
- src/navigation/AppNavigator.tsx (fix) → fix/app-navigation
662
- src/hooks/useAuth.ts (modified) → refactor/auth-hook
663
- android/ + ios/ (configs) → chore/native-config
664
- src/screens/Auth* + src/services/auth* → feature/authentication
665
- src/components/ (multiple) → refactor/ui-components
666
- ```
667
-
668
- 2. **Warn user:**
669
-
670
- ```
671
- ⚠️ Working on protected branch '[branch-name]' with uncommitted changes.
672
-
673
- Analyzed changes:
674
- - [file1] (new)
675
- - [file2] (modified)
676
- - [file3] (modified)
677
- ... [N] more files
678
-
679
- Detected type: [feature|fix|refactor|chore]
680
- Suggested branch: [type]/[descriptive-slug]
681
- ```
682
-
683
- 3. **Offer options:**
684
- - **A)** Create branch: `[type]/[suggested-name]`
685
- - **B)** Edit branch name (user provides custom slug)
686
- - **C)** Stash changes and continue: `git stash`
687
- - **D)** Cancel
688
-
689
- 4. If user chooses A:
690
-
691
- ```bash
692
- git checkout -b [type]/[suggested-name]
693
- ```
694
-
695
- Then show:
696
-
697
- ```
698
- Created and switched to '[type]/[suggested-name]'
699
-
700
- Next steps:
701
- 1. Run /flow-commit to commit these changes
702
- 2. Return to protected branch: git checkout [protected-branch]
703
- 3. Continue with /flow-work for new task
704
-
705
- Or continue working on this branch if it's your intended work.
706
- ```
707
-
708
- 5. If user chooses B:
709
- ```
710
- Enter branch name (without type prefix): _
711
- ```
712
- Then create: `[detected-type]/[user-input]`
713
-
714
- **B) If NO uncommitted changes:**
715
-
716
- - Proceed normally - creating work branches FROM protected branches is correct workflow
717
- - Protected branches serve as base for new work
718
-
719
- 1. **Generate Branch Name**:
720
- - `feature/[slug]`
721
- - `refactor/[slug]`
722
- - `fix/[slug]`
723
- 2. **Execute**: `git checkout -b [branch-name]`.
724
- 3. **Update `status.json`**: Record branch name and start timestamp.
725
- 4. **Implementation**: Proceed according to the selected mode (Auto, Phase-by-phase, Task-by-task).
726
- - Follow tasks in `work.md`
727
- - Update task checkboxes as completed
728
- - Update `status.json` progress
729
-
730
- ---
731
-
732
- ## Phase 4: Finalization (User-Controlled)
733
-
734
- **⚠️ SKIP THIS PHASE IF complexity == "SIMPLE"** (already handled in Phase 1.5)
735
-
736
- **Trigger Options:**
737
-
738
- - User types: `/flow-work complete`
739
- - All checkboxes in work.md marked complete
740
- - User explicitly requests finalization
741
-
742
- **CRITICAL: This phase requires EXPLICIT user confirmations at each step.**
743
-
744
- ---
745
-
746
- ### Step 1: Validation Check
747
-
748
- ```
749
- 🔍 Running validation...
750
- ```
751
-
752
- Execute:
753
-
754
- ```bash
755
- npm test # or project-specific test command
756
- npm run lint # or project-specific lint command
757
- ```
758
-
759
- Show results:
760
-
761
- ```
762
- 📊 Validation Results
763
-
764
- Tests: [✅ Passed | ❌ Failed (N tests)]
765
- Lint: [✅ Clean | ⚠️ N warnings | ❌ N errors]
766
- Coverage: [X%]
767
-
768
- Proceed with finalization?
769
-
770
- a) Yes, continue
771
- b) No, let me fix issues
772
- c) Skip validation (not recommended)
773
-
774
- Your choice: _
775
- ```
776
-
777
- - **'b'**: Return to Phase 3 for fixes, END finalization
778
- - **'c'**: Show warning, ask confirmation again, then continue
779
- - **'a'**: Continue to Step 2
780
-
781
- ---
782
-
783
- ### Step 2: Source Documentation Update (Interactive)
784
-
785
- **Detect source references:**
786
-
787
- ```python
788
- source = extract_from_work_md_or_status_json()
789
- # Returns: "HU-001-002" | "roadmap-2.3" | "manual" | None
790
- ```
791
-
792
- **IF source exists (HU or roadmap):**
793
-
794
- ```
795
- 📚 Update Source Documentation?
796
-
797
- Found:
798
- - planning/roadmap.md → Feature 2.3 "User Authentication"
799
- - planning/user-stories/EP-001/HU-001-002.md
800
-
801
- What to update?
802
-
803
- a) Update both
804
- b) Update roadmap only
805
- c) Update user story only
806
- d) Skip (I'll update manually later)
807
-
808
- Your choice: _
809
- ```
810
-
811
- **Execute selected updates:**
812
-
813
- - Read files
814
- - Mark checkboxes as complete: `- [ ]` → `- [x]`
815
- - Add timestamp comment: `<!-- Completed: YYYY-MM-DD HH:MM -->`
816
- - Save files
817
-
818
- **Show confirmation:**
819
-
820
- ```
821
- Updated:
822
- - planning/roadmap.md (Feature 2.3)
823
- - planning/user-stories/EP-001/HU-001-002.md (5/5 DoD items)
824
- ```
825
-
826
- **IF update fails:**
827
-
828
- ```
829
- Failed to update [file]: [reason]
830
-
831
- Options:
832
- 1) Retry update
833
- 2) Skip this file
834
- 3) Cancel finalization
835
-
836
- Your choice: _
837
- ```
838
-
839
- **IF source is "manual" or None:**
840
-
841
- ```
842
- ⏭️ No source documentation to update (manual task)
843
- ```
844
-
845
- ---
846
-
847
- ### Step 3: Archiving Decision (Explicit Confirmation)
848
-
849
- **Show current state:**
850
-
851
- ```bash
852
- git diff --stat
853
- git log --oneline origin/[base-branch]..HEAD
854
- ```
855
-
856
- **Present archiving options:**
857
-
858
- ```
859
- 💾 Task Completion Options
860
-
861
- Current work:
862
- - Branch: [branch-name]
863
- - Files changed: [N]
864
- - Commits: [N]
865
- - Duration: [X min]
866
-
867
- What do you want to do?
868
-
869
- a) Complete & Archive
870
- → Record analytics, delete work files, clean state
871
-
872
- b) Complete & Keep
873
- Record analytics, rename folder to [task]-completed
874
-
875
- c) Mark as Paused
876
- Keep work files for later resume
877
-
878
- d) Cancel
879
- → Go back to editing
880
-
881
- Your choice: _
882
- ```
883
-
884
- **IF 'a' (Complete & Archive):**
885
-
886
- ```
887
- ✅ Archiving task...
888
- ```
889
-
890
- 1. **Extract metadata:**
891
-
892
- ```javascript
893
- // IF complexity == "COMPLEX" (has status.json):
894
- analytics = {
895
- task: '[task-name]',
896
- type: '[feature|refactor|fix]',
897
- src: '[HU-001-002|roadmap-2.3|manual]',
898
- dur: Math.round((completed - created) / 60000), // minutes
899
- start: timestamps.created,
900
- end: new Date().toISOString(),
901
- tasks: progress.totalTasks,
902
- sp: extract_story_points_from_work_md(),
903
- commits: git.commits.length,
904
- valid: validation.tests.passed && validation.lint.passed,
905
- };
906
-
907
- // IF complexity == "MEDIUM" (only work.md):
908
- analytics = {
909
- task: '[task-name]',
910
- type: '[detected-from-folder-name]',
911
- src: 'manual',
912
- dur: estimate_duration_from_git_log(),
913
- start: get_first_commit_timestamp(),
914
- end: new Date().toISOString(),
915
- tasks: count_checkboxes_in_work_md(),
916
- sp: extract_story_points_from_work_md() || null,
917
- commits: count_commits_in_branch(),
918
- valid: validation_passed,
919
- };
920
- ```
921
-
922
- 2. **Append to analytics:**
923
-
924
- ```bash
925
- echo '{json}' >> .ai-flow/archive/analytics.jsonl
926
- ```
927
-
928
- 3. **Delete work folder:**
929
-
930
- ```bash
931
- rm -rf .ai-flow/work/[task-name]/
932
- ```
933
-
934
- 4. **Show confirmation:**
935
-
936
- ```
937
- ✅ Task archived successfully
938
-
939
- 📊 Analytics recorded:
940
- - Duration: [X] min
941
- - Story Points: [N]
942
- - Commits: [N]
943
- - Validation: [✅ Passed | ❌ Failed]
944
- ```
945
-
946
- **IF 'b' (Complete & Keep):**
947
-
948
- 1. Record analytics (same as 'a')
949
- 2. Rename folder:
950
- ```bash
951
- mv .ai-flow/work/[task] .ai-flow/work/[task]-completed/
952
- ```
953
- 3. Show: `✅ Task marked complete. Files kept in: .ai-flow/work/[task]-completed/`
954
-
955
- **IF 'c' (Mark as Paused):**
956
-
957
- 1. Add marker file:
958
- ```bash
959
- echo "Paused: $(date)" > .ai-flow/work/[task]/PAUSED
960
- ```
961
- 2. Show: `⏸️ Task paused. Resume with: /flow-work`
962
- 3. **END finalization**
963
-
964
- **IF 'd' (Cancel):**
965
-
966
- 1. Show: `❌ Finalization cancelled. Task remains active.`
967
- 2. **END finalization**
968
-
969
- ---
970
-
971
- ### Step 4: Ticket Summary (Optional)
972
-
973
- **Only ask if task was archived (option 'a' or 'b'):**
974
-
975
- ```
976
- 📋 Generate ticket summary?
977
-
978
- (For ClickUp, Jira, Linear, Asana, Trello, GitHub Projects, etc.)
979
-
980
- y/n: _
981
- ```
982
-
983
- **IF 'y':**
984
-
985
- 1. Check if template exists:
986
-
987
- ```bash
988
- [ -f .ai-flow/prompts/shared/task-summary-template.md ]
989
- ```
990
-
991
- 2. **IF template exists:**
992
- - Read template
993
- - Extract data from:
994
- - Last line of `analytics.jsonl`
995
- - Git stats: `git diff --stat`, `git log --oneline`
996
- - Branch info
997
- - Populate template with real data
998
- - Show formatted summary
999
-
1000
- 3. **IF template doesn't exist:**
1001
- - Generate basic summary:
1002
-
1003
- ```
1004
- 📋 Task Summary
1005
-
1006
- **Task**: [task-name]
1007
- **Type**: [feature|refactor|fix]
1008
- **Duration**: [X min]
1009
- **Story Points**: [N]
1010
- **Commits**: [N]
1011
- **Branch**: [branch-name]
1012
- **Status**: Complete
1013
-
1014
- **Changes**:
1015
- [git diff --stat output]
1016
-
1017
- **Commits**:
1018
- [git log --oneline output]
1019
- ```
1020
-
1021
- 4. Show: `📋 Copy the summary above to your ticket system`
1022
-
1023
- **IF 'n':**
1024
-
1025
- ```
1026
- ⏭️ Skipping ticket summary
1027
- ```
1028
-
1029
- ---
1030
-
1031
- ### Step 5: Git Push (Final Step)
1032
-
1033
- ```
1034
- 🚀 Push changes to remote?
1035
-
1036
- git push origin [branch-name]
1037
-
1038
- y/n: _
1039
- ```
1040
-
1041
- **IF 'y':**
1042
-
1043
- ```bash
1044
- git push origin [branch-name]
1045
- ```
1046
-
1047
- Show result:
1048
-
1049
- ```
1050
- Pushed to origin/[branch-name]
1051
-
1052
- Next steps:
1053
- - Create Pull Request/Merge Request
1054
- - Request code review
1055
- - Update project board
1056
- ```
1057
-
1058
- **IF 'n':**
1059
-
1060
- ```
1061
- ⏭️ Skipping push
1062
-
1063
- ⚠️ Remember to push later:
1064
- git push origin [branch-name]
1065
- ```
1066
-
1067
- ---
1068
-
1069
- ### Finalization Complete
1070
-
1071
- ```
1072
- ✅ Task Finalization Complete
1073
-
1074
- 📊 Summary:
1075
- - [✅|⚠️] Validation passed
1076
- - [✅|⏭️] Documentation updated
1077
- - [✅|⏭️] Task archived
1078
- - [✅|⏭️] Ticket summary generated
1079
- - [✅|⏭️] Pushed to remote
1080
-
1081
- Task: [task-name]
1082
- Branch: [branch-name]
1083
- Duration: [X min]
1084
- Commits: [N]
1085
-
1086
- 🎉 Great work!
1087
- ```
1088
-
1089
- **END WORKFLOW**
1090
-
1091
- ---
1092
-
1093
- ## Orchestration Rules
1094
-
1095
- - **DRY Logic**: This file handles the high-level orchestration.
1096
- - **Delegation**:
1097
- - Detailed Feature logic`@flow-work-feature.md`
1098
- - Detailed Refactor logic`@flow-work-refactor.md`
1099
- - Detailed Fix logic`@flow-work-fix.md`
1100
- - Resume logic`@flow-work-resume.md`
1101
- - **State Persistence**: Always read/write to `.ai-flow/work/[name]/status.json` to maintain state across sessions.
1102
-
1103
- ---
1104
-
1105
- ## Phase 99: Informative Response
1106
-
1107
- **This phase handles questions, reports, and analysis requests WITHOUT creating work files or branches.**
1108
-
1109
- ### 1. Analyze Request Type
1110
-
1111
- **Classify the informative request:**
1112
-
1113
- - **Technical Question:** How does X work? Why do we use Y?
1114
- - **Screen/Component Explanation:** Explain this screen/component/hook
1115
- - **Architecture Review:** Show me the navigation structure/state management
1116
- - **Project Report:** Generate report on dependencies/performance/bundle size
1117
- - **File Location:** Where is X screen? Find Y component
1118
- - **Comparison:** Compare X vs Y approach (React Native vs Flutter)
1119
- - **Best Practices:** What's the best way to handle X in mobile?
1120
-
1121
- ### 2. Load Relevant Context
1122
-
1123
- **Based on request type, load specific documentation:**
1124
-
1125
- **IF question about architecture/patterns:**
1126
-
1127
- - Read `ai-instructions.md` (NEVER/ALWAYS rules)
1128
- - Read `docs/architecture.md` (navigation, state, native modules)
1129
- - Search codebase for examples
1130
-
1131
- **IF question about specific screen/component:**
1132
-
1133
- - Search codebase for screen/component files
1134
- - Read relevant specs from `specs/`
1135
- - Check navigation flow
1136
-
1137
- **IF report request:**
1138
-
1139
- - Run appropriate analysis (performance, dependencies, native modules)
1140
- - Read relevant docs for context
1141
- - Generate structured report
1142
-
1143
- **IF file location request:**
1144
-
1145
- - Search codebase with grep/semantic search
1146
- - List relevant screens/components with descriptions
1147
-
1148
- ### 3. Provide Comprehensive Answer
1149
-
1150
- **Structure your response:**
1151
-
1152
- ```markdown
1153
- ## [Question/Request]
1154
-
1155
- ### Answer
1156
-
1157
- [Detailed explanation with code examples if relevant]
1158
-
1159
- ### Related Documentation
1160
-
1161
- - [Link to relevant docs]
1162
- - [Link to screen/component examples]
1163
-
1164
- ### Additional Context
1165
-
1166
- [Architecture decisions, mobile-specific considerations, performance implications]
1167
-
1168
- ### Related User Stories/Features
1169
-
1170
- [If applicable, link to planning docs]
1171
- ```
1172
-
1173
- **Guidelines:**
1174
-
1175
- - **Be comprehensive:** Load all relevant context, don't guess
1176
- - **Show examples:** Include actual code from the project
1177
- - **Reference docs:** Link to `docs/`, `specs/`, `planning/`
1178
- - **Explain trade-offs:** Why was X chosen over Y?
1179
- - **Mobile-specific:** Consider iOS vs Android differences
1180
- - **Provide sources:** Always cite where information comes from
1181
-
1182
- ### 4. Offer Follow-up Actions
1183
-
1184
- **After answering, offer next steps:**
1185
-
1186
- ```
1187
- ✅ Answer provided.
1188
-
1189
- Would you like me to:
1190
- A) Implement changes based on this analysis
1191
- B) Create a work plan for improvements
1192
- C) Generate a spec/doc for this
1193
- D) Nothing, just the answer
1194
-
1195
- Your choice (or just ask another question): _
1196
- ```
1197
-
1198
- **IF user chooses A or B:**
1199
-
1200
- - Return to Phase 0 with refined objective
1201
- - Create appropriate work.md and proceed with execution
1202
-
1203
- **IF user chooses C:**
1204
-
1205
- - Create spec/doc file in appropriate location
1206
- - Commit with descriptive message
1207
-
1208
- **IF user chooses D or asks another question:**
1209
-
1210
- - **END WORKFLOW** (no files created, no branches)
1211
-
1212
- ### 5. Example Interactions
1213
-
1214
- **Example 1: Technical Question**
1215
-
1216
- ````
1217
- User: /flow-work ¿cómo funciona la navegación entre screens?
1218
-
1219
- Agent:
1220
- 🔍 Detected: Informative request (question)
1221
-
1222
- ## How Navigation Works in This Project
1223
-
1224
- ### Implementation
1225
-
1226
- We use React Navigation v6 with stack and tab navigators:
1227
- - Main structure in `src/navigation/AppNavigator.tsx`
1228
- - Tab navigator: `TabNavigator.tsx` (Home, Search, Profile)
1229
- - Auth stack: `AuthNavigator.tsx` (Login, Register)
1230
-
1231
- [Shows actual code from project]
1232
-
1233
- ### Navigation Flow
1234
- ```typescript
1235
- // AppNavigator.tsx
1236
- const AppNavigator = () => {
1237
- const { isAuthenticated } = useAuth();
1238
-
1239
- return (
1240
- <NavigationContainer>
1241
- {isAuthenticated ? <TabNavigator /> : <AuthNavigator />}
1242
- </NavigationContainer>
1243
- );
1244
- };
1245
- ````
1246
-
1247
- ### Screen Transitions
1248
-
1249
- - Stack: `navigation.navigate('ScreenName', { params })`
1250
- - Modal: `navigation.push('Modal')`
1251
- - Go back: `navigation.goBack()`
1252
-
1253
- ### Deep Linking
1254
-
1255
- Configured in `linking.ts` for:
1256
-
1257
- - `/home` → HomeScreen
1258
- - `/profile/:id` → ProfileScreen
1259
- - `/post/:id` → PostDetailScreen
1260
-
1261
- ### Platform Differences
1262
-
1263
- - iOS: Native stack with gestures
1264
- - Android: Material transitions
1265
- - Handled automatically by React Navigation
1266
-
1267
- ### Related Documentation
1268
-
1269
- - `docs/architecture.md` - Navigation structure
1270
- - `docs/components.md` - Screen components
1271
-
1272
- Would you like me to implement any changes to navigation? (Y/N): \_
1273
-
1274
- ```
1275
-
1276
- **Example 2: Report Request**
1277
-
1278
- ```
1279
-
1280
- User: /flow-work genera un informe de dependencias nativas
1281
-
1282
- Agent:
1283
- 🔍 Detected: Informative request (report)
1284
-
1285
- ## Native Dependencies Report
1286
-
1287
- [Analyzes package.json and native modules]
1288
-
1289
- ### Total Native Modules: 8
1290
-
1291
- | Module | Version | Platform | Purpose |
1292
- | ------------------------------ | ------- | -------- | ------------------ |
1293
- | react-native-permissions | 3.8.0 | Both | Runtime perms |
1294
- | react-native-camera | 4.2.1 | Both | Camera access |
1295
- | @react-native-async-storage | 1.19.0 | Both | Local storage |
1296
- | react-native-push-notification | 8.1.1 | Both | Push notifications |
1297
- | react-native-geolocation | 2.1.0 | Both | GPS location |
1298
- | react-native-biometrics | 3.0.1 | Both | Face/Touch ID |
1299
- | react-native-keychain | 8.1.2 | Both | Secure storage |
1300
- | react-native-vector-icons | 9.2.0 | Both | Icon library |
1301
-
1302
- ### Pod Dependencies (iOS): 15 pods
1303
-
1304
- ### Gradle Dependencies (Android): 12 libraries
1305
-
1306
- ### Potential Issues
1307
-
1308
- 1. ⚠️ `react-native-camera` - Consider migrating to `react-native-vision-camera` (better performance)
1309
- 2. All modules support New Architecture
1310
- 3. No deprecated packages
1311
-
1312
- ### Bundle Impact
1313
-
1314
- - iOS: +2.5 MB (native modules)
1315
- - Android: +3.1 MB (native modules)
1316
-
1317
- ### Recommendations
1318
-
1319
- 1. Migrate camera module for better performance
1320
- 2. All modules are up to date ✅
1321
-
1322
- Would you like me to create a migration plan for the camera module? (Y/N): \_
1323
-
1324
- ```
1325
-
1326
- ---
1327
-
1328
- **BEGIN EXECUTION when user runs `/flow-work [args]`**
1329
- ```
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/mobile/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: 'mobile',
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/mobile/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 (React Native Paper, React Navigation, 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: 'mobile',
493
+ });
494
+ ```
495
+
496
+ **IF `analysisResult.success === false`:**
497
+
498
+ ```
499
+ API Analysis Failed
500
+
501
+ Error: ${analysisResult.error}
502
+ Details: ${analysisResult.details}
503
+
504
+ Suggestions:
505
+ ${analysisResult.suggestions.map((s, i) => ` ${i+1}. ${s}`).join('\n')}
506
+
507
+ The API URL might have changed or the backend spec is invalid.
508
+
509
+ Options:
510
+ A) Update URL and retry
511
+ B) Clear cache and try default URL
512
+ C) Proceed with manual mode (no OpenAPI analysis)
513
+ D) Cancel
514
+
515
+ Your choice: _
516
+ ```
517
+
518
+ **User selects:**
519
+
520
+ - **A**: Prompt for new URL, save to cache, retry Phase 0.1
521
+ - **B**: Clear cache, use default, retry Phase 0.1
522
+ - **C**: Switch to `FEATURE` mode, continue without OpenAPI
523
+ - **D**: Abort workflow
524
+
525
+ ### Step 4: Enrich Workflow Context
526
+
527
+ Merge analysis into workflow context for use in subsequent phases:
528
+
529
+ ```typescript
530
+ workflow_context = {
531
+ ...workflow_context,
532
+
533
+ // From API analysis
534
+ projectStandards: analysisResult.projectStandards,
535
+ openapi: analysisResult.openapi,
536
+ endpoints: analysisResult.endpoints,
537
+ schemas: analysisResult.schemas,
538
+ fields: analysisResult.fields,
539
+ features: analysisResult.features,
540
+ relationships: analysisResult.relationships,
541
+
542
+ // For Phase 2 (work.md generation)
543
+ template: 'api-module', // Use specialized template
544
+
545
+ // For Phase 0.5 (complexity override)
546
+ complexity_override: analysisResult.complexity.level,
547
+ estimatedSP: analysisResult.complexity.estimatedSP,
548
+ estimatedHours: analysisResult.complexity.estimatedHours,
549
+ };
550
+ ```
551
+
552
+ ### Step 5: Show Analysis Summary
553
+
554
+ Present structured summary to user (condensed version):
555
+
556
+ ```
557
+ 📋 API Module Analysis Summary
558
+
559
+ 📊 Module: ${moduleName}
560
+ 🔗 API: ${apiUrl}
561
+
562
+ 📐 Detected Project Stack:
563
+ UI: ${projectStandards.stack.ui}
564
+ List: ${projectStandards.stack.list} ✅
565
+ Forms: ${projectStandards.stack.forms} + ${projectStandards.stack.validation} ✅
566
+ Data: ${projectStandards.stack.query}
567
+ Navigation: ${projectStandards.stack.navigation} ✅
568
+
569
+ 🔧 Endpoints: ${endpoints.length} detected
570
+ 📦 Entity: ${schemas.response.fields.length} fields
571
+ 🔗 Relationships: ${relationships.length}
572
+ 🏗️ Complexity: ${complexity.level} (${complexity.estimatedHours}h estimated)
573
+
574
+ All standards locked. Module will match existing patterns.
575
+
576
+ Proceeding to Phase 0.5...
577
+ ```
578
+
579
+ ### Step 6: Continue to Phase 0.5
580
+
581
+ With enriched context, proceed to complexity classification.
582
+
583
+ **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.
584
+
585
+ ---
586
+
587
+ ## Phase 0.5: Complexity Classification (CRITICAL)
588
+
589
+ **Analyze task scope to determine workflow:**
590
+
591
+ | Metric | SIMPLE (⚡) | MEDIUM (📝) | COMPLEX (🏗️) |
592
+ | ------------- | ----------- | ----------- | ------------- |
593
+ | Files | 1 | 2-5 | >5 |
594
+ | Lines | <20 | 20-100 | >100 |
595
+ | Tests | No | Optional | Required |
596
+ | Docs | None | Minor | Significant |
597
+ | Architecture | None | Minimal | Major changes |
598
+ | Time estimate | <15 min | 15-60 min | >60 min |
599
+
600
+ **Classification Rules:**
601
+
602
+ **⚡ SIMPLE Task:**
603
+
604
+ - Examples: Fix typo, rename variable, update constant, add log, adjust styling
605
+ - **Workflow**: In-chat plan → Execute → Done (NO files created)
606
+ - **Context**: Only `ai-instructions.md` if relevant
607
+
608
+ **📝 MEDIUM Task:**
609
+
610
+ - Examples: Add component, refactor hook, simple bug fix, update screen
611
+ - **Workflow**: Create `work.md` only (NO `status.json`) → Execute → Simple archive
612
+ - **Context**: Load 2-3 relevant docs
613
+
614
+ **🏗️ COMPLEX Task:**
615
+
616
+ - Examples: New feature, major refactor, security fix, multi-screen changes
617
+ - **Workflow**: Full workflow (`work.md` + `status.json` + branch + archiving)
618
+ - **Context**: Load all relevant docs
619
+
620
+ **Detection Logic:**
621
+
622
+ ```python
623
+ # Special case: API_MODULE mode (complexity already determined)
624
+ if mode == "API_MODULE":
625
+ complexity = workflow_context.complexity_override # From API analyzer
626
+ elif files_affected == 1 and lines_changed < 20 and no_tests_needed and no_architecture_impact:
627
+ complexity = "SIMPLE"
628
+ elif files_affected <= 5 and lines_changed <= 100 and architecture_impact == "minimal":
629
+ complexity = "MEDIUM"
630
+ else:
631
+ complexity = "COMPLEX"
632
+ ```
633
+
634
+ **Show classification:**
635
+
636
+ ```
637
+ 🔍 Task Complexity: [SIMPLE ⚡ | MEDIUM 📝 | COMPLEX 🏗️]
638
+
639
+ Detected:
640
+ - Files: [N]
641
+ - Estimated lines: [~X]
642
+ - Tests needed: [Yes/No]
643
+ - Architecture impact: [None/Minimal/Major]
644
+
645
+ Proceeding with [SIMPLE/MEDIUM/COMPLEX] workflow.
646
+ ```
647
+
648
+ ---
649
+
650
+ ## Phase 1: Analysis & Refinement
651
+
652
+ **1. Context Loading (Smart & Selective):**
653
+
654
+ **CRITICAL: Load context based on task complexity and type:**
655
+
656
+ **IF complexity == "SIMPLE":**
657
+
658
+ - Load ONLY `ai-instructions.md` if task involves code changes
659
+ - Skip all other documentation
660
+ - Use existing patterns in nearby code as reference
661
+
662
+ **IF complexity == "MEDIUM":**
663
+
664
+ - Load `ai-instructions.md` (core rules)
665
+ - Load 1-2 specific docs based on task type:
666
+ - UI changes → `docs/components.md`
667
+ - Navigation → `docs/navigation.md`
668
+ - Security → `specs/security.md`
669
+ - Skip architecture.md unless creating new patterns
670
+
671
+ **IF complexity == "COMPLEX":**
672
+
673
+ - Load `ai-instructions.md` (NEVER/ALWAYS rules)
674
+ - Load `docs/architecture.md` (patterns, structure)
675
+ - Load task-specific docs:
676
+ - UI → `docs/components.md`
677
+ - Security/Auth `specs/security.md`
678
+ - Navigation → `docs/navigation.md`
679
+ - Tests → `docs/testing.md`
680
+ - Load `docs/code-standards.md` only if creating new files
681
+
682
+ **Source Documentation (User Stories/Roadmap):**
683
+
684
+ **IF** `HU-XXX-XXX` or roadmap feature provided:
685
+
686
+ - **`planning/roadmap.md`**: Load for high-level scope
687
+ - **`planning/user-stories/**/HU-XXX-XXX.md`\*\*: Load for detailed requirements
688
+
689
+ **2. Detail Level Detection (if Manual input):**
690
+
691
+ IF input is manual description (not HU/Roadmap):
692
+
693
+ ```python
694
+ detail_level = analyze_description(input)
695
+
696
+ # Criteria for HIGH detail (Feature):
697
+ # - Mentions technology/method (JWT, OAuth, bcrypt, etc.)
698
+ # - Describes flow (registration, login, CRUD, etc.)
699
+ # - Includes technical constraints (hashing, tokens, validation, etc.)
700
+
701
+ # Criteria for HIGH detail (Refactor):
702
+ # - Describes what to extract/move
703
+ # - Mentions destination (file/class)
704
+ # - References pattern to follow
705
+
706
+ # Criteria for HIGH detail (Fix):
707
+ # - Describes symptom (error 500, crash, null pointer, etc.)
708
+ # - Mentions probable cause
709
+ # - Suggests fix approach
710
+ ```
711
+
712
+ **3. Interactive Refinement (Conditional):**
713
+
714
+ **IF detail_level == "HIGH":**
715
+
716
+ - Skip refinement questions
717
+ - Proceed directly to Phase 2 (Planning)
718
+ - Show: "✅ Sufficient detail detected. Proceeding with planning..."
719
+
720
+ **IF detail_level == "MEDIUM":**
721
+
722
+ - Ask 1-2 targeted questions (only missing items)
723
+ - Use Multiple Choice with defaults (⭐)
724
+
725
+ **IF detail_level == "LOW":**
726
+
727
+ - Full refinement flow (3-5 questions)
728
+ - Use Multiple Choice with defaults (⭐)
729
+ - Focus on: approach, scope, constraints, priorities
730
+
731
+ **Example Interaction (LOW detail):**
732
+
733
+ > 📝 I need to clarify some details for this feature:
734
+ >
735
+ > 1. What authentication provider should we use? [default: A]
736
+ > A) JWT (Local) ⭐
737
+ > B) OAuth2 (Google/GitHub)
738
+ > C) Firebase Auth
739
+ > 2. Should we implement audit logs for this? [default: B]
740
+ > A) Yes
741
+ > B) No ⭐
742
+ >
743
+ > Your answers (or Enter for defaults): \_
744
+
745
+ **4. Refined Objective Generation (if Manual):**
746
+
747
+ After refinement, generate clear objective statement:
748
+
749
+ ```
750
+ ✅ Refined Objective:
751
+
752
+ [Clear 1-2 paragraph description of WHAT will be implemented]
753
+
754
+ **Scope**:
755
+ - [List in-scope items]
756
+
757
+ **Out of Scope**:
758
+ - [List out-of-scope items]
759
+
760
+ Is this correct? (Yes/Edit/Cancel): _
761
+ ```
762
+
763
+ **5. Documentation Compliance Check:**
764
+
765
+ Read relevant documentation:
766
+
767
+ - `ai-instructions.md` (NEVER/ALWAYS rules)
768
+ - `docs/architecture.md` (patterns, structure)
769
+ - `docs/code-standards.md` (naming, quality)
770
+ - IF auth/security: `specs/security.md`
771
+ - IF database: `docs/data-model.md`
772
+ - IF API: `docs/api.md`
773
+
774
+ Compare refined objective against documentation:
775
+
776
+ **IF deviation detected:**
777
+
778
+ ```
779
+ 🚨 POTENTIAL DEVIATION
780
+
781
+ From [document]:
782
+ ❌ NEVER: [rule being violated]
783
+ ALWAYS: [rule being ignored]
784
+
785
+ Your request: [conflicting part]
786
+
787
+ Options:
788
+ A) Modify request to align with documentation
789
+ B) Proceed with deviation (requires justification)
790
+ C) Cancel
791
+
792
+ Your choice: _
793
+ ```
794
+
795
+ **IF user chooses B (Override):**
796
+
797
+ ```
798
+ ⚠️ OVERRIDE CONFIRMATION
799
+
800
+ You are implementing something that deviates from:
801
+ - [list violated documents/rules]
802
+
803
+ Type "I UNDERSTAND THE RISKS" to proceed: _
804
+
805
+ Provide justification: _
806
+ ```
807
+
808
+ ---
809
+
810
+ ## Phase 1.5: SIMPLE Task Fast-Track
811
+
812
+ **IF complexity == "SIMPLE": Execute immediately without creating files**
813
+
814
+ 1. **Show in-chat plan:**
815
+
816
+ ```
817
+ ⚡ SIMPLE Task - Fast Execution
818
+
819
+ What: [1-line description]
820
+ File: [path]
821
+ Change: [specific modification]
822
+ Lines: ~[N] (estimated)
823
+
824
+ Execute now? (y/n): _
825
+ ```
826
+
827
+ 2. **IF user confirms ('y'):**
828
+ - Make the change immediately
829
+ - Show git diff preview
830
+ - Skip to Phase 3 (no branch creation if already on feature branch)
831
+ - Show: "✅ Done. Run `/flow-commit` to commit."
832
+ - **END WORKFLOW** (no archiving needed)
833
+
834
+ 3. **IF user declines ('n'):**
835
+ - Cancel task
836
+ - **END WORKFLOW**
837
+
838
+ **Note:** SIMPLE tasks don't create work.md, status.json, or archive records.
839
+
840
+ ---
841
+
842
+ ## Phase 2: Planning & Documentation
843
+
844
+ **⚠️ SKIP THIS PHASE IF complexity == "SIMPLE"**
845
+
846
+ **1. Read Required Documentation (Based on Complexity)**
847
+
848
+ **IF complexity == "MEDIUM":**
849
+
850
+ - `ai-instructions.md` (core rules)
851
+ - Load ONLY task-specific docs:
852
+ - UI → `docs/components.md`
853
+ - Navigation `docs/navigation.md`
854
+ - Security → `specs/security.md`
855
+
856
+ **IF complexity == "COMPLEX":**
857
+
858
+ - `ai-instructions.md` (NEVER/ALWAYS rules)
859
+ - `docs/architecture.md` (layer, pattern, structure)
860
+ - Task-specific docs:
861
+ - UI → `docs/components.md`
862
+ - Security/Auth → `specs/security.md`
863
+ - Navigation `docs/navigation.md`
864
+ - Tests → `docs/testing.md`
865
+ - `docs/code-standards.md` (only if creating new files)
866
+
867
+ **2. Analyze Existing Codebase (MANDATORY)**
868
+
869
+ Find similar features/patterns in codebase:
870
+
871
+ - Identify existing files to use as reference (e.g., ProfileScreen.tsx for SettingsScreen.tsx)
872
+ - Check naming conventions in actual code
873
+ - Verify architectural consistency
874
+ - Look for reusable components/hooks
875
+
876
+ **3. Generate work.md (Conditional)**
877
+
878
+ **IF complexity == "MEDIUM":**
879
+
880
+ - Create simplified `.ai-flow/work/[task-name]/work.md` (~15-20 lines)
881
+ - Skip status.json
882
+
883
+ **IF complexity == "COMPLEX":**
884
+
885
+ - Create full `.ai-flow/work/[task-name]/work.md` (~30-40 lines)
886
+ - Create `status.json` (see step 4)
887
+
888
+ **Structure for MEDIUM tasks** (~15-20 lines):
889
+
890
+ ```markdown
891
+ # [Type]: [Feature Name]
892
+
893
+ **Source**: [HU-XXX | Roadmap X.X | Manual]
894
+ **Files**: [2-5 files listed]
895
+ **Estimated**: [20-60 min]
896
+
897
+ ## Objective
898
+
899
+ [1 clear paragraph]
900
+
901
+ ## Tasks
902
+
903
+ - [ ] Task 1 → path/file.tsx
904
+ - [ ] Task 2 → path/file.ts
905
+ - [ ] Task 3 (optional tests)
906
+
907
+ ## Key Rules
908
+
909
+ - [1-2 relevant ALWAYS rules]
910
+ - [1-2 relevant NEVER rules]
911
+ ```
912
+
913
+ **Structure for COMPLEX tasks** (~30-40 lines):
914
+
915
+ ```markdown
916
+ # [Type]: [Feature Name]
917
+
918
+ ## Context
919
+
920
+ **Source**: HU-001-002 | Roadmap 2.3 | Manual [+ DEVIATION if override]
921
+ **SP**: 5 | **Branch**: feature/user-auth | **Deps**: None
922
+
923
+ ## Objective
924
+
925
+ [1-2 clear paragraphs describing WHAT will be implemented]
926
+
927
+ ## Documentation Constraints
928
+
929
+ **Read**: ai-instructions.md, architecture.md, code-standards.md, [security.md]
930
+
931
+ **Key Rules**:
932
+
933
+ - ✅ ALWAYS: [List specific rules that apply]
934
+ - NEVER: [List specific prohibitions]
935
+ - 📐 Pattern: [Architectural pattern from docs]
936
+ - 📁 Location: [File structure from architecture.md]
937
+
938
+ ## Approach
939
+
940
+ **Layer**: [Data | Business Logic | API | UI]
941
+ **Files**: [List files to create/modify]
942
+ **Reference**: [Existing file to follow as pattern]
943
+
944
+ **Phases**:
945
+
946
+ 1. [Phase 1 description]
947
+ 2. [Phase 2 description]
948
+ 3. [Phase 3 description]
949
+ 4. [Phase 4 description]
950
+
951
+ ## Tasks
952
+
953
+ [SEE TASK GENERATION LOGIC BELOW]
954
+
955
+ ## Validation
956
+
957
+ - [ ] All NEVER/ALWAYS rules followed
958
+ - [ ] Tests pass (coverage per docs/testing.md)
959
+ - [ ] No hardcoded secrets
960
+ - [ ] Follows existing patterns
961
+ - [ ] [Add specific validations based on type]
962
+ ```
963
+
964
+ **Task Generation Logic:**
965
+
966
+ **IF source is User Story:**
967
+
968
+ ```python
969
+ tasks = read_user_story_tasks()
970
+ if tasks.are_detailed(): # Has: path, constraints, SP, deps
971
+ work_md.tasks = """
972
+ **Source**: planning/user-stories/EP-XXX/HU-XXX-XXX.md
973
+
974
+ Tasks already detailed in User Story (see linked file).
975
+
976
+ **Summary**: [N] tasks, [X] SP total
977
+ - [Brief phase breakdown]
978
+ """
979
+ else:
980
+ work_md.tasks = generate_detailed_tasks()
981
+ ```
982
+
983
+ **IF source is Roadmap:**
984
+
985
+ ```python
986
+ feature = read_roadmap_feature()
987
+ if feature.has_detailed_tasks():
988
+ work_md.tasks = """
989
+ **Source**: planning/roadmap.md Feature X.X
990
+
991
+ Tasks already detailed in Roadmap (see linked file).
992
+
993
+ **Summary**: [N] tasks, [X] SP total
994
+ """
995
+ else:
996
+ work_md.tasks = generate_detailed_tasks()
997
+ ```
998
+
999
+ **IF source is Manual OR tasks need expansion:**
1000
+
1001
+ Generate detailed tasks with this format:
1002
+
1003
+ ```markdown
1004
+ ## Tasks
1005
+
1006
+ **Source**: Manual | Roadmap X.X (expanded) | HU-XXX-XXX (expanded)
1007
+
1008
+ - [ ] T001 [D] Create User entity → src/entities/User.ts • 1 SP
1009
+ - Follow Product.ts pattern, hash passwords (bcrypt)
1010
+ - [ ] T002 [L] UserService.register() → src/services/ • 2 SP
1011
+ - Validate email, hash password, return JWT (deps: T001)
1012
+ - [ ] T003 [A] POST /users/register → src/controllers/ • 1 SP
1013
+ - Return 201, rate limit, follow api.md (deps: T002)
1014
+ - [ ] T004 [T] Unit tests → tests/services/ • 2 SP
1015
+ - 80% coverage, edge cases (deps: T002)
1016
+ ```
1017
+
1018
+ **Task Detail Requirements:**
1019
+
1020
+ - Specific file path
1021
+ - Pattern/reference to follow
1022
+ - Key constraints from docs
1023
+ - Dependencies (if applicable)
1024
+ - Story Points
1025
+
1026
+ **4. Generate status.json (ONLY for COMPLEX tasks)**
1027
+
1028
+ **IF complexity == "COMPLEX":**
1029
+
1030
+ Create: `.ai-flow/work/[task-name]/status.json`
1031
+
1032
+ ```json
1033
+ {
1034
+ "type": "feature|refactor|fix",
1035
+ "source": "HU-001-002|roadmap-2.3|manual",
1036
+ "deviation": false,
1037
+ "progress": {
1038
+ "totalTasks": 4,
1039
+ "completedTasks": 0,
1040
+ "percentage": 0
1041
+ },
1042
+ "git": {
1043
+ "branchName": "feature/user-auth",
1044
+ "commits": []
1045
+ },
1046
+ "timestamps": {
1047
+ "created": "2025-12-22T23:00:00-03:00",
1048
+ "lastUpdated": "2025-12-22T23:00:00-03:00"
1049
+ },
1050
+ "validation": {
1051
+ "tests": { "executed": false },
1052
+ "lint": { "executed": false }
1053
+ }
1054
+ }
1055
+ ```
1056
+
1057
+ **5. User Approval**
1058
+
1059
+ Show work.md for review:
1060
+
1061
+ ```
1062
+ 📄 Generated: .ai-flow/work/[task-name]/work.md
1063
+
1064
+ Review work.md? (Yes/Edit/No): _
1065
+ ```
1066
+
1067
+ - **Yes**: Proceed to Phase 3
1068
+ - **Edit**: Allow user to modify work.md, then re-read
1069
+ - **No**: Cancel workflow
1070
+
1071
+ ---
1072
+
1073
+ ## Phase 3: Execution (Branch Creation)
1074
+
1075
+ **Upon confirmation to start implementation:**
1076
+
1077
+ **🛡️ CRITICAL: Protected Branch Check**
1078
+
1079
+ ```bash
1080
+ git branch --show-current
1081
+ git status --porcelain
1082
+ ```
1083
+
1084
+ **If current branch is protected** (`main`, `master`, `develop`, `development`):
1085
+
1086
+ **A) If there are uncommitted changes:**
1087
+
1088
+ 1. **Analyze changes to generate branch name:**
1089
+
1090
+ ```bash
1091
+ git status --porcelain
1092
+ git diff --stat
1093
+ ```
1094
+
1095
+ **Detection rules:**
1096
+ - **New screens/features** → `feature/`
1097
+ - **Bug fixes** (crash fixes, error handling) → `fix/`
1098
+ - **Refactoring/Optimization** (code improvements, performance) `refactor/`
1099
+ - **Native configs** (android/, ios/, dependencies) → `chore/`
1100
+ - **Tests only** → `test/`
1101
+ - **Documentation only** `docs/`
1102
+
1103
+ **Naming strategy:**
1104
+ - Extract screen/module/feature name
1105
+ - Remove extensions (.tsx, .ts, .js)
1106
+ - Convert to kebab-case
1107
+ - Limit to 3-4 words max
1108
+
1109
+ **Examples:**
1110
+
1111
+ ```
1112
+ src/screens/ProfileScreen.tsx (new) → feature/profile-screen
1113
+ src/navigation/AppNavigator.tsx (fix) → fix/app-navigation
1114
+ src/hooks/useAuth.ts (modified) → refactor/auth-hook
1115
+ android/ + ios/ (configs) → chore/native-config
1116
+ src/screens/Auth* + src/services/auth* → feature/authentication
1117
+ src/components/ (multiple) → refactor/ui-components
1118
+ ```
1119
+
1120
+ 2. **Warn user:**
1121
+
1122
+ ```
1123
+ ⚠️ Working on protected branch '[branch-name]' with uncommitted changes.
1124
+
1125
+ Analyzed changes:
1126
+ - [file1] (new)
1127
+ - [file2] (modified)
1128
+ - [file3] (modified)
1129
+ ... [N] more files
1130
+
1131
+ Detected type: [feature|fix|refactor|chore]
1132
+ Suggested branch: [type]/[descriptive-slug]
1133
+ ```
1134
+
1135
+ 3. **Offer options:**
1136
+ - **A)** Create branch: `[type]/[suggested-name]` ⭐
1137
+ - **B)** Edit branch name (user provides custom slug)
1138
+ - **C)** Stash changes and continue: `git stash`
1139
+ - **D)** Cancel
1140
+
1141
+ 4. If user chooses A:
1142
+
1143
+ ```bash
1144
+ git checkout -b [type]/[suggested-name]
1145
+ ```
1146
+
1147
+ Then show:
1148
+
1149
+ ```
1150
+ Created and switched to '[type]/[suggested-name]'
1151
+
1152
+ Next steps:
1153
+ 1. Run /flow-commit to commit these changes
1154
+ 2. Return to protected branch: git checkout [protected-branch]
1155
+ 3. Continue with /flow-work for new task
1156
+
1157
+ Or continue working on this branch if it's your intended work.
1158
+ ```
1159
+
1160
+ 5. If user chooses B:
1161
+ ```
1162
+ Enter branch name (without type prefix): _
1163
+ ```
1164
+ Then create: `[detected-type]/[user-input]`
1165
+
1166
+ **B) If NO uncommitted changes:**
1167
+
1168
+ - Proceed normally - creating work branches FROM protected branches is correct workflow
1169
+ - Protected branches serve as base for new work
1170
+
1171
+ 1. **Generate Branch Name**:
1172
+ - `feature/[slug]`
1173
+ - `refactor/[slug]`
1174
+ - `fix/[slug]`
1175
+ 2. **Execute**: `git checkout -b [branch-name]`.
1176
+ 3. **Update `status.json`**: Record branch name and start timestamp.
1177
+ 4. **Implementation**: Proceed according to the selected mode (Auto, Phase-by-phase, Task-by-task).
1178
+ - Follow tasks in `work.md`
1179
+ - Update task checkboxes as completed
1180
+ - Update `status.json` progress
1181
+
1182
+ ---
1183
+
1184
+ ## Phase 4: Finalization (User-Controlled)
1185
+
1186
+ **⚠️ SKIP THIS PHASE IF complexity == "SIMPLE"** (already handled in Phase 1.5)
1187
+
1188
+ **Trigger Options:**
1189
+
1190
+ - User types: `/flow-work complete`
1191
+ - All checkboxes in work.md marked complete
1192
+ - User explicitly requests finalization
1193
+
1194
+ ---
1195
+
1196
+ ### Source Documentation Update (Interactive)
1197
+
1198
+ **Detect source references:**
1199
+
1200
+ ```python
1201
+ source = extract_from_work_md_or_status_json()
1202
+ # Returns: "HU-001-002" | "roadmap-2.3" | "manual" | None
1203
+ ```
1204
+
1205
+ **IF source exists (HU or roadmap):**
1206
+
1207
+ ```
1208
+ 📚 Update Source Documentation?
1209
+
1210
+ Found:
1211
+ - planning/roadmap.md → Feature 2.3 "User Authentication"
1212
+ - planning/user-stories/EP-001/HU-001-002.md
1213
+
1214
+ What to update?
1215
+
1216
+ a) Update both ⭐
1217
+ b) Update roadmap only
1218
+ c) Update user story only
1219
+ d) Skip (I'll update manually later)
1220
+
1221
+ Your choice: _
1222
+ ```
1223
+
1224
+ **Execute selected updates:**
1225
+
1226
+ - Read files
1227
+ - Mark checkboxes as complete: `- [ ]` → `- [x]`
1228
+ - Add timestamp comment: `<!-- Completed: YYYY-MM-DD HH:MM -->`
1229
+ - Save files
1230
+
1231
+ **Show confirmation:**
1232
+
1233
+ ```
1234
+ ✅ Updated:
1235
+ - planning/roadmap.md (Feature 2.3)
1236
+ - planning/user-stories/EP-001/HU-001-002.md (5/5 DoD items)
1237
+ ```
1238
+
1239
+ **IF update fails:**
1240
+
1241
+ ```
1242
+ ❌ Failed to update [file]: [reason]
1243
+
1244
+ Options:
1245
+ 1) Retry update
1246
+ 2) Skip this file
1247
+ 3) Cancel finalization
1248
+
1249
+ Your choice: _
1250
+ ```
1251
+
1252
+ **IF source is "manual" or None:**
1253
+
1254
+ ```
1255
+ ⏭️ No source documentation to update (manual task)
1256
+ ```
1257
+
1258
+ ---
1259
+
1260
+ ## ✅ Development Work Complete
1261
+
1262
+ Your code is ready for finalization. You have two options:
1263
+
1264
+ ### Option A: Run Full Finalization Now (Recommended) ⭐
1265
+
1266
+ Execute `/flow-finish` to complete all finalization steps automatically:
1267
+
1268
+ - ✅ **Smart Validation** - Runs tests + lint only if needed (or revalidates if requested)
1269
+ - 📦 **Work Archiving** - Records analytics to `.ai-flow/archive/analytics.jsonl`, cleans workspace
1270
+ - 🤖 **AI-Powered Summaries** - Generates professional PR/Jira descriptions (~1,200 tokens)
1271
+ - 🚀 **Optional Push** - Pushes to remote with explicit confirmation
1272
+
1273
+ **To proceed:** Type `/flow-finish` in the chat
1274
+
1275
+ ---
1276
+
1277
+ ### Option B: Manual Finalization
1278
+
1279
+ If you prefer granular control over each step:
1280
+
1281
+ 1. **Validation:** `/flow-check` - Run comprehensive validation (tests + code review)
1282
+ 2. **Commit:** `/flow-commit` - Create conventional commit with auto-generated message
1283
+ 3. **Archive:** Manually record analytics and clean `.ai-flow/work/[task-name]/`
1284
+ 4. **Push:** `git push origin [branch-name]` when ready
1285
+
1286
+ ---
1287
+
1288
+ **What would you like to do?**
1289
+
1290
+ ```
1291
+ a) Run /flow-finish now (Recommended - comprehensive automation)
1292
+ b) I'll handle finalization manually (granular control)
1293
+ c) Tell me more about what /flow-finish does
1294
+
1295
+ Your choice: _
1296
+ ```
1297
+
1298
+ **If 'a':** Execute `/flow-finish` immediately
1299
+
1300
+ **If 'b':** Show confirmation and end workflow:
1301
+
1302
+ ```
1303
+ ✅ Understood. Development complete.
1304
+
1305
+ 📋 Manual finalization checklist:
1306
+ - [ ] Run validation: /flow-check
1307
+ - [ ] Commit changes: /flow-commit
1308
+ - [ ] Archive work folder
1309
+ - [ ] Push to remote
1310
+ - [ ] Create PR/MR
1311
+
1312
+ 💡 Tip: You can run /flow-finish anytime to automate these steps.
1313
+
1314
+ 🎉 Great work!
1315
+ ```
1316
+
1317
+ **If 'c':** Show detailed explanation:
1318
+
1319
+ ```
1320
+ 📖 About /flow-finish
1321
+
1322
+ /flow-finish is an intelligent finalization workflow that:
1323
+
1324
+ 1️⃣ **Smart Validation (Step 1)**
1325
+ - Detects if /flow-check was already run successfully
1326
+ - Only re-runs if explicitly requested or validation failed
1327
+ - Shows comprehensive test + lint results
1328
+
1329
+ 2️⃣ **Smart Commit (Step 2)**
1330
+ - Detects uncommitted changes automatically
1331
+ - Runs /flow-commit only if needed
1332
+ - Generates conventional commit messages
1333
+
1334
+ 3️⃣ **Work Archiving (Step 3)**
1335
+ - Extracts analytics: duration, story points, commits
1336
+ - Appends to .ai-flow/archive/analytics.jsonl
1337
+ - Deletes .ai-flow/work/[task-name]/ folder
1338
+
1339
+ 4️⃣ **AI Summaries (Step 4)**
1340
+ - Reads git diff + commit history
1341
+ - Generates professional PR description
1342
+ - Generates ticket update (Jira/ClickUp/Linear)
1343
+ - ~1,200 tokens, markdown-formatted
1344
+
1345
+ 5️⃣ **Optional Push (Step 5)**
1346
+ - Always asks for confirmation
1347
+ - Shows branch name and remote
1348
+ - Never pushes without explicit approval
1349
+
1350
+ **Would you like to run it now?** (y/n): _
1351
+ ```
1352
+
1353
+ **END WORKFLOW**
1354
+
1355
+ ---
1356
+
1357
+ ## Orchestration Rules
1358
+
1359
+ - **DRY Logic**: This file handles the high-level orchestration.
1360
+ - **Delegation**:
1361
+ - Detailed Feature logic → `@flow-work-feature.md`
1362
+ - Detailed Refactor logic → `@flow-work-refactor.md`
1363
+ - Detailed Fix logic → `@flow-work-fix.md`
1364
+ - Resume logic → `@flow-work-resume.md`
1365
+ - **State Persistence**: Always read/write to `.ai-flow/work/[name]/status.json` to maintain state across sessions.
1366
+
1367
+ ---
1368
+
1369
+ ## Phase 99: Informative Response
1370
+
1371
+ **This phase handles questions, reports, and analysis requests WITHOUT creating work files or branches.**
1372
+
1373
+ ### 1. Analyze Request Type
1374
+
1375
+ **Classify the informative request:**
1376
+
1377
+ - **Technical Question:** How does X work? Why do we use Y?
1378
+ - **Screen/Component Explanation:** Explain this screen/component/hook
1379
+ - **Architecture Review:** Show me the navigation structure/state management
1380
+ - **Project Report:** Generate report on dependencies/performance/bundle size
1381
+ - **File Location:** Where is X screen? Find Y component
1382
+ - **Comparison:** Compare X vs Y approach (React Native vs Flutter)
1383
+ - **Best Practices:** What's the best way to handle X in mobile?
1384
+
1385
+ ### 2. Load Relevant Context
1386
+
1387
+ **Based on request type, load specific documentation:**
1388
+
1389
+ **IF question about architecture/patterns:**
1390
+
1391
+ - Read `ai-instructions.md` (NEVER/ALWAYS rules)
1392
+ - Read `docs/architecture.md` (navigation, state, native modules)
1393
+ - Search codebase for examples
1394
+
1395
+ **IF question about specific screen/component:**
1396
+
1397
+ - Search codebase for screen/component files
1398
+ - Read relevant specs from `specs/`
1399
+ - Check navigation flow
1400
+
1401
+ **IF report request:**
1402
+
1403
+ - Run appropriate analysis (performance, dependencies, native modules)
1404
+ - Read relevant docs for context
1405
+ - Generate structured report
1406
+
1407
+ **IF file location request:**
1408
+
1409
+ - Search codebase with grep/semantic search
1410
+ - List relevant screens/components with descriptions
1411
+
1412
+ ### 3. Provide Comprehensive Answer
1413
+
1414
+ **Structure your response:**
1415
+
1416
+ ```markdown
1417
+ ## [Question/Request]
1418
+
1419
+ ### Answer
1420
+
1421
+ [Detailed explanation with code examples if relevant]
1422
+
1423
+ ### Related Documentation
1424
+
1425
+ - [Link to relevant docs]
1426
+ - [Link to screen/component examples]
1427
+
1428
+ ### Additional Context
1429
+
1430
+ [Architecture decisions, mobile-specific considerations, performance implications]
1431
+
1432
+ ### Related User Stories/Features
1433
+
1434
+ [If applicable, link to planning docs]
1435
+ ```
1436
+
1437
+ **Guidelines:**
1438
+
1439
+ - **Be comprehensive:** Load all relevant context, don't guess
1440
+ - **Show examples:** Include actual code from the project
1441
+ - **Reference docs:** Link to `docs/`, `specs/`, `planning/`
1442
+ - **Explain trade-offs:** Why was X chosen over Y?
1443
+ - **Mobile-specific:** Consider iOS vs Android differences
1444
+ - **Provide sources:** Always cite where information comes from
1445
+
1446
+ ### 4. Offer Follow-up Actions
1447
+
1448
+ **After answering, offer next steps:**
1449
+
1450
+ ```
1451
+ ✅ Answer provided.
1452
+
1453
+ Would you like me to:
1454
+ A) Implement changes based on this analysis
1455
+ B) Create a work plan for improvements
1456
+ C) Generate a spec/doc for this
1457
+ D) Nothing, just the answer
1458
+
1459
+ Your choice (or just ask another question): _
1460
+ ```
1461
+
1462
+ **IF user chooses A or B:**
1463
+
1464
+ - Return to Phase 0 with refined objective
1465
+ - Create appropriate work.md and proceed with execution
1466
+
1467
+ **IF user chooses C:**
1468
+
1469
+ - Create spec/doc file in appropriate location
1470
+ - Commit with descriptive message
1471
+
1472
+ **IF user chooses D or asks another question:**
1473
+
1474
+ - **END WORKFLOW** (no files created, no branches)
1475
+
1476
+ ### 5. Example Interactions
1477
+
1478
+ **Example 1: Technical Question**
1479
+
1480
+ ````
1481
+ User: /flow-work ¿cómo funciona la navegación entre screens?
1482
+
1483
+ Agent:
1484
+ 🔍 Detected: Informative request (question)
1485
+
1486
+ ## How Navigation Works in This Project
1487
+
1488
+ ### Implementation
1489
+
1490
+ We use React Navigation v6 with stack and tab navigators:
1491
+ - Main structure in `src/navigation/AppNavigator.tsx`
1492
+ - Tab navigator: `TabNavigator.tsx` (Home, Search, Profile)
1493
+ - Auth stack: `AuthNavigator.tsx` (Login, Register)
1494
+
1495
+ [Shows actual code from project]
1496
+
1497
+ ### Navigation Flow
1498
+ ```typescript
1499
+ // AppNavigator.tsx
1500
+ const AppNavigator = () => {
1501
+ const { isAuthenticated } = useAuth();
1502
+
1503
+ return (
1504
+ <NavigationContainer>
1505
+ {isAuthenticated ? <TabNavigator /> : <AuthNavigator />}
1506
+ </NavigationContainer>
1507
+ );
1508
+ };
1509
+ ````
1510
+
1511
+ ### Screen Transitions
1512
+
1513
+ - Stack: `navigation.navigate('ScreenName', { params })`
1514
+ - Modal: `navigation.push('Modal')`
1515
+ - Go back: `navigation.goBack()`
1516
+
1517
+ ### Deep Linking
1518
+
1519
+ Configured in `linking.ts` for:
1520
+
1521
+ - `/home` → HomeScreen
1522
+ - `/profile/:id` → ProfileScreen
1523
+ - `/post/:id` → PostDetailScreen
1524
+
1525
+ ### Platform Differences
1526
+
1527
+ - iOS: Native stack with gestures
1528
+ - Android: Material transitions
1529
+ - Handled automatically by React Navigation
1530
+
1531
+ ### Related Documentation
1532
+
1533
+ - `docs/architecture.md` - Navigation structure
1534
+ - `docs/components.md` - Screen components
1535
+
1536
+ Would you like me to implement any changes to navigation? (Y/N): \_
1537
+
1538
+ ```
1539
+
1540
+ **Example 2: Report Request**
1541
+
1542
+ ```
1543
+
1544
+ User: /flow-work genera un informe de dependencias nativas
1545
+
1546
+ Agent:
1547
+ 🔍 Detected: Informative request (report)
1548
+
1549
+ ## Native Dependencies Report
1550
+
1551
+ [Analyzes package.json and native modules]
1552
+
1553
+ ### Total Native Modules: 8
1554
+
1555
+ | Module | Version | Platform | Purpose |
1556
+ | ------------------------------ | ------- | -------- | ------------------ |
1557
+ | react-native-permissions | 3.8.0 | Both | Runtime perms |
1558
+ | react-native-camera | 4.2.1 | Both | Camera access |
1559
+ | @react-native-async-storage | 1.19.0 | Both | Local storage |
1560
+ | react-native-push-notification | 8.1.1 | Both | Push notifications |
1561
+ | react-native-geolocation | 2.1.0 | Both | GPS location |
1562
+ | react-native-biometrics | 3.0.1 | Both | Face/Touch ID |
1563
+ | react-native-keychain | 8.1.2 | Both | Secure storage |
1564
+ | react-native-vector-icons | 9.2.0 | Both | Icon library |
1565
+
1566
+ ### Pod Dependencies (iOS): 15 pods
1567
+
1568
+ ### Gradle Dependencies (Android): 12 libraries
1569
+
1570
+ ### Potential Issues
1571
+
1572
+ 1. ⚠️ `react-native-camera` - Consider migrating to `react-native-vision-camera` (better performance)
1573
+ 2. ✅ All modules support New Architecture
1574
+ 3. ✅ No deprecated packages
1575
+
1576
+ ### Bundle Impact
1577
+
1578
+ - iOS: +2.5 MB (native modules)
1579
+ - Android: +3.1 MB (native modules)
1580
+
1581
+ ### Recommendations
1582
+
1583
+ 1. Migrate camera module for better performance
1584
+ 2. All modules are up to date ✅
1585
+
1586
+ Would you like me to create a migration plan for the camera module? (Y/N): \_
1587
+
1588
+ ```
1589
+
1590
+ ---
1591
+
1592
+ **BEGIN EXECUTION when user runs `/flow-work [args]`**
1593
+ ```