ai-flow-dev 2.6.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 (33) hide show
  1. package/README.md +24 -21
  2. package/package.json +6 -6
  3. package/prompts/backend/flow-check-review.md +648 -12
  4. package/prompts/backend/flow-check-test.md +520 -8
  5. package/prompts/backend/flow-check.md +687 -29
  6. package/prompts/backend/flow-commit.md +18 -49
  7. package/prompts/backend/flow-finish.md +919 -0
  8. package/prompts/backend/flow-release.md +949 -0
  9. package/prompts/backend/flow-work.md +296 -221
  10. package/prompts/desktop/flow-check-review.md +648 -12
  11. package/prompts/desktop/flow-check-test.md +520 -8
  12. package/prompts/desktop/flow-check.md +687 -29
  13. package/prompts/desktop/flow-commit.md +18 -49
  14. package/prompts/desktop/flow-finish.md +910 -0
  15. package/prompts/desktop/flow-release.md +662 -0
  16. package/prompts/desktop/flow-work.md +398 -219
  17. package/prompts/frontend/flow-check-review.md +648 -12
  18. package/prompts/frontend/flow-check-test.md +520 -8
  19. package/prompts/frontend/flow-check.md +687 -29
  20. package/prompts/frontend/flow-commit.md +18 -49
  21. package/prompts/frontend/flow-finish.md +910 -0
  22. package/prompts/frontend/flow-release.md +519 -0
  23. package/prompts/frontend/flow-work-api.md +1540 -0
  24. package/prompts/frontend/flow-work.md +774 -218
  25. package/prompts/mobile/flow-check-review.md +648 -12
  26. package/prompts/mobile/flow-check-test.md +520 -8
  27. package/prompts/mobile/flow-check.md +687 -29
  28. package/prompts/mobile/flow-commit.md +18 -49
  29. package/prompts/mobile/flow-finish.md +910 -0
  30. package/prompts/mobile/flow-release.md +751 -0
  31. package/prompts/mobile/flow-work-api.md +1493 -0
  32. package/prompts/mobile/flow-work.md +792 -222
  33. package/templates/AGENT.template.md +1 -1
@@ -27,12 +27,95 @@ Provide a single, intelligent entry point for all development work (New Features
27
27
 
28
28
  ---
29
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
+
30
112
  ## Phase 0: Detection & Strategy (Automatic)
31
113
 
32
114
  **1. Semantic Analysis of Input:**
33
115
 
34
116
  | Input Pattern | Mode | Source / Action |
35
117
  | ------------------------------ | ----------------- | -------------------------------------------------------------------- |
118
+ | `api\s+([a-z0-9\-_]+)` | `API_MODULE` | Invoke `.ai-flow/prompts/mobile/flow-work-api.md` analyzer |
36
119
  | `HU-\d{3}-\d{3}` | `USER_STORY` | Load from `planning/user-stories/**/HU-XXX-XXX.md` |
37
120
  | `EP-\d{3}` | `EPIC` | Analyze/List User Stories for Epic `EP-XXX` |
38
121
  | `T\d{3}(-T\d{3})?` | `TASKS` | Target specific task or range (e.g., `T025-T030`) |
@@ -53,6 +136,454 @@ Provide a single, intelligent entry point for all development work (New Features
53
136
 
54
137
  ---
55
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
+
56
587
  ## Phase 0.5: Complexity Classification (CRITICAL)
57
588
 
58
589
  **Analyze task scope to determine workflow:**
@@ -89,7 +620,10 @@ Provide a single, intelligent entry point for all development work (New Features
89
620
  **Detection Logic:**
90
621
 
91
622
  ```python
92
- if files_affected == 1 and lines_changed < 20 and no_tests_needed and no_architecture_impact:
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:
93
627
  complexity = "SIMPLE"
94
628
  elif files_affected <= 5 and lines_changed <= 100 and architecture_impact == "minimal":
95
629
  complexity = "MEDIUM"
@@ -657,48 +1191,9 @@ git status --porcelain
657
1191
  - All checkboxes in work.md marked complete
658
1192
  - User explicitly requests finalization
659
1193
 
660
- **CRITICAL: This phase requires EXPLICIT user confirmations at each step.**
661
-
662
1194
  ---
663
1195
 
664
- ### Step 1: Validation Check
665
-
666
- ```
667
- 🔍 Running validation...
668
- ```
669
-
670
- Execute:
671
-
672
- ```bash
673
- npm test # or project-specific test command
674
- npm run lint # or project-specific lint command
675
- ```
676
-
677
- Show results:
678
-
679
- ```
680
- 📊 Validation Results
681
-
682
- Tests: [✅ Passed | ❌ Failed (N tests)]
683
- Lint: [✅ Clean | ⚠️ N warnings | ❌ N errors]
684
- Coverage: [X%]
685
-
686
- Proceed with finalization?
687
-
688
- a) Yes, continue ⭐
689
- b) No, let me fix issues
690
- c) Skip validation (not recommended)
691
-
692
- Your choice: _
693
- ```
694
-
695
- - **'b'**: Return to Phase 3 for fixes, END finalization
696
- - **'c'**: Show warning, ask confirmation again, then continue
697
- - **'a'**: Continue to Step 2
698
-
699
- ---
700
-
701
- ### Step 2: Source Documentation Update (Interactive)
1196
+ ### Source Documentation Update (Interactive)
702
1197
 
703
1198
  **Detect source references:**
704
1199
 
@@ -762,262 +1257,337 @@ Your choice: _
762
1257
 
763
1258
  ---
764
1259
 
765
- ### Step 3: Archiving Decision (Explicit Confirmation)
1260
+ ## Development Work Complete
766
1261
 
767
- **Show current state:**
1262
+ Your code is ready for finalization. You have two options:
768
1263
 
769
- ```bash
770
- git diff --stat
771
- git log --oneline origin/[base-branch]..HEAD
772
- ```
1264
+ ### Option A: Run Full Finalization Now (Recommended) ⭐
773
1265
 
774
- **Present archiving options:**
1266
+ Execute `/flow-finish` to complete all finalization steps automatically:
775
1267
 
776
- ```
777
- 💾 Task Completion Options
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
778
1272
 
779
- Current work:
780
- - Branch: [branch-name]
781
- - Files changed: [N]
782
- - Commits: [N]
783
- - Duration: [X min]
1273
+ **To proceed:** Type `/flow-finish` in the chat
784
1274
 
785
- What do you want to do?
1275
+ ---
786
1276
 
787
- a) Complete & Archive
788
- → Record analytics, delete work files, clean state
1277
+ ### Option B: Manual Finalization
789
1278
 
790
- b) Complete & Keep
791
- → Record analytics, rename folder to [task]-completed
1279
+ If you prefer granular control over each step:
792
1280
 
793
- c) Mark as Paused
794
- Keep work files for later resume
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
795
1285
 
796
- d) Cancel
797
- → Go back to editing
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
798
1294
 
799
1295
  Your choice: _
800
1296
  ```
801
1297
 
802
- **IF 'a' (Complete & Archive):**
803
-
804
- ```
805
- ✅ Archiving task...
806
- ```
807
-
808
- 1. **Extract metadata:**
809
-
810
- ```javascript
811
- // IF complexity == "COMPLEX" (has status.json):
812
- analytics = {
813
- task: '[task-name]',
814
- type: '[feature|refactor|fix]',
815
- src: '[HU-001-002|roadmap-2.3|manual]',
816
- dur: Math.round((completed - created) / 60000), // minutes
817
- start: timestamps.created,
818
- end: new Date().toISOString(),
819
- tasks: progress.totalTasks,
820
- sp: extract_story_points_from_work_md(),
821
- commits: git.commits.length,
822
- valid: validation.tests.passed && validation.lint.passed,
823
- };
824
-
825
- // IF complexity == "MEDIUM" (only work.md):
826
- analytics = {
827
- task: '[task-name]',
828
- type: '[detected-from-folder-name]',
829
- src: 'manual',
830
- dur: estimate_duration_from_git_log(),
831
- start: get_first_commit_timestamp(),
832
- end: new Date().toISOString(),
833
- tasks: count_checkboxes_in_work_md(),
834
- sp: extract_story_points_from_work_md() || null,
835
- commits: count_commits_in_branch(),
836
- valid: validation_passed,
837
- };
838
- ```
1298
+ **If 'a':** Execute `/flow-finish` immediately
839
1299
 
840
- 2. **Append to analytics:**
1300
+ **If 'b':** Show confirmation and end workflow:
841
1301
 
842
- ```bash
843
- echo '{json}' >> .ai-flow/archive/analytics.jsonl
844
- ```
1302
+ ```
1303
+ Understood. Development complete.
845
1304
 
846
- 3. **Delete work folder:**
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
847
1311
 
848
- ```bash
849
- rm -rf .ai-flow/work/[task-name]/
850
- ```
1312
+ 💡 Tip: You can run /flow-finish anytime to automate these steps.
851
1313
 
852
- 4. **Show confirmation:**
1314
+ 🎉 Great work!
1315
+ ```
853
1316
 
854
- ```
855
- ✅ Task archived successfully
1317
+ **If 'c':** Show detailed explanation:
856
1318
 
857
- 📊 Analytics recorded:
858
- - Duration: [X] min
859
- - Story Points: [N]
860
- - Commits: [N]
861
- - Validation: [✅ Passed | ❌ Failed]
862
- ```
1319
+ ```
1320
+ 📖 About /flow-finish
863
1321
 
864
- **IF 'b' (Complete & Keep):**
1322
+ /flow-finish is an intelligent finalization workflow that:
865
1323
 
866
- 1. Record analytics (same as 'a')
867
- 2. Rename folder:
868
- ```bash
869
- mv .ai-flow/work/[task] .ai-flow/work/[task]-completed/
870
- ```
871
- 3. Show: `✅ Task marked complete. Files kept in: .ai-flow/work/[task]-completed/`
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
872
1328
 
873
- **IF 'c' (Mark as Paused):**
1329
+ 2️⃣ **Smart Commit (Step 2)**
1330
+ - Detects uncommitted changes automatically
1331
+ - Runs /flow-commit only if needed
1332
+ - Generates conventional commit messages
874
1333
 
875
- 1. Add marker file:
876
- ```bash
877
- echo "Paused: $(date)" > .ai-flow/work/[task]/PAUSED
878
- ```
879
- 2. Show: `⏸️ Task paused. Resume with: /flow-work`
880
- 3. **END finalization**
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
881
1338
 
882
- **IF 'd' (Cancel):**
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
883
1344
 
884
- 1. Show: `❌ Finalization cancelled. Task remains active.`
885
- 2. **END finalization**
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**
886
1354
 
887
1355
  ---
888
1356
 
889
- ### Step 4: Ticket Summary (Optional)
1357
+ ## Orchestration Rules
890
1358
 
891
- **Only ask if task was archived (option 'a' or 'b'):**
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.
892
1366
 
893
- ```
894
- 📋 Generate ticket summary?
1367
+ ---
895
1368
 
896
- (For ClickUp, Jira, Linear, Asana, Trello, GitHub Projects, etc.)
1369
+ ## Phase 99: Informative Response
897
1370
 
898
- y/n: _
899
- ```
1371
+ **This phase handles questions, reports, and analysis requests WITHOUT creating work files or branches.**
900
1372
 
901
- **IF 'y':**
1373
+ ### 1. Analyze Request Type
902
1374
 
903
- 1. Check if template exists:
1375
+ **Classify the informative request:**
904
1376
 
905
- ```bash
906
- [ -f .ai-flow/prompts/shared/task-summary-template.md ]
907
- ```
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?
908
1384
 
909
- 2. **IF template exists:**
910
- - Read template
911
- - Extract data from:
912
- - Last line of `analytics.jsonl`
913
- - Git stats: `git diff --stat`, `git log --oneline`
914
- - Branch info
915
- - Populate template with real data
916
- - Show formatted summary
1385
+ ### 2. Load Relevant Context
917
1386
 
918
- 3. **IF template doesn't exist:**
919
- - Generate basic summary:
1387
+ **Based on request type, load specific documentation:**
920
1388
 
921
- ```
922
- 📋 Task Summary
1389
+ **IF question about architecture/patterns:**
923
1390
 
924
- **Task**: [task-name]
925
- **Type**: [feature|refactor|fix]
926
- **Duration**: [X min]
927
- **Story Points**: [N]
928
- **Commits**: [N]
929
- **Branch**: [branch-name]
930
- **Status**: ✅ Complete
1391
+ - Read `ai-instructions.md` (NEVER/ALWAYS rules)
1392
+ - Read `docs/architecture.md` (navigation, state, native modules)
1393
+ - Search codebase for examples
931
1394
 
932
- **Changes**:
933
- [git diff --stat output]
1395
+ **IF question about specific screen/component:**
934
1396
 
935
- **Commits**:
936
- [git log --oneline output]
937
- ```
1397
+ - Search codebase for screen/component files
1398
+ - Read relevant specs from `specs/`
1399
+ - Check navigation flow
938
1400
 
939
- 4. Show: `📋 Copy the summary above to your ticket system`
1401
+ **IF report request:**
940
1402
 
941
- **IF 'n':**
1403
+ - Run appropriate analysis (performance, dependencies, native modules)
1404
+ - Read relevant docs for context
1405
+ - Generate structured report
942
1406
 
943
- ```
944
- ⏭️ Skipping ticket summary
945
- ```
1407
+ **IF file location request:**
946
1408
 
947
- ---
1409
+ - Search codebase with grep/semantic search
1410
+ - List relevant screens/components with descriptions
948
1411
 
949
- ### Step 5: Git Push (Final Step)
1412
+ ### 3. Provide Comprehensive Answer
950
1413
 
951
- ```
952
- 🚀 Push changes to remote?
1414
+ **Structure your response:**
953
1415
 
954
- git push origin [branch-name]
1416
+ ```markdown
1417
+ ## [Question/Request]
955
1418
 
956
- y/n: _
957
- ```
1419
+ ### Answer
958
1420
 
959
- **IF 'y':**
1421
+ [Detailed explanation with code examples if relevant]
960
1422
 
961
- ```bash
962
- git push origin [branch-name]
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]
963
1435
  ```
964
1436
 
965
- Show result:
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:**
966
1449
 
967
1450
  ```
968
- Pushed to origin/[branch-name]
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
969
1458
 
970
- Next steps:
971
- - Create Pull Request/Merge Request
972
- - Request code review
973
- - Update project board
1459
+ Your choice (or just ask another question): _
974
1460
  ```
975
1461
 
976
- **IF 'n':**
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): \_
977
1537
 
978
1538
  ```
979
- ⏭️ Skipping push
980
1539
 
981
- ⚠️ Remember to push later:
982
- git push origin [branch-name]
1540
+ **Example 2: Report Request**
1541
+
983
1542
  ```
984
1543
 
985
- ---
1544
+ User: /flow-work genera un informe de dependencias nativas
986
1545
 
987
- ### Finalization Complete
1546
+ Agent:
1547
+ 🔍 Detected: Informative request (report)
988
1548
 
989
- ```
990
- ✅ Task Finalization Complete
1549
+ ## Native Dependencies Report
991
1550
 
992
- 📊 Summary:
993
- - [✅|⚠️] Validation passed
994
- - [✅|⏭️] Documentation updated
995
- - [✅|⏭️] Task archived
996
- - [✅|⏭️] Ticket summary generated
997
- - [✅|⏭️] Pushed to remote
1551
+ [Analyzes package.json and native modules]
998
1552
 
999
- Task: [task-name]
1000
- Branch: [branch-name]
1001
- Duration: [X min]
1002
- Commits: [N]
1553
+ ### Total Native Modules: 8
1003
1554
 
1004
- 🎉 Great work!
1005
- ```
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 |
1006
1565
 
1007
- **END WORKFLOW**
1566
+ ### Pod Dependencies (iOS): 15 pods
1008
1567
 
1009
- ---
1568
+ ### Gradle Dependencies (Android): 12 libraries
1010
1569
 
1011
- ## Orchestration Rules
1570
+ ### Potential Issues
1012
1571
 
1013
- - **DRY Logic**: This file handles the high-level orchestration.
1014
- - **Delegation**:
1015
- - Detailed Feature logic → `@flow-work-feature.md`
1016
- - Detailed Refactor logic → `@flow-work-refactor.md`
1017
- - Detailed Fix logic → `@flow-work-fix.md`
1018
- - Resume logic → `@flow-work-resume.md`
1019
- - **State Persistence**: Always read/write to `.ai-flow/work/[name]/status.json` to maintain state across sessions.
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
+ ```
1020
1589
 
1021
1590
  ---
1022
1591
 
1023
1592
  **BEGIN EXECUTION when user runs `/flow-work [args]`**
1593
+ ```