elsabro 2.1.0 → 2.3.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 (64) hide show
  1. package/agents/elsabro-orchestrator.md +113 -0
  2. package/commands/elsabro/add-phase.md +17 -0
  3. package/commands/elsabro/add-todo.md +111 -53
  4. package/commands/elsabro/audit-milestone.md +19 -0
  5. package/commands/elsabro/check-todos.md +210 -31
  6. package/commands/elsabro/complete-milestone.md +20 -1
  7. package/commands/elsabro/debug.md +19 -0
  8. package/commands/elsabro/discuss-phase.md +18 -1
  9. package/commands/elsabro/execute.md +511 -58
  10. package/commands/elsabro/insert-phase.md +18 -1
  11. package/commands/elsabro/list-phase-assumptions.md +17 -0
  12. package/commands/elsabro/new-milestone.md +19 -0
  13. package/commands/elsabro/new.md +19 -0
  14. package/commands/elsabro/pause-work.md +19 -0
  15. package/commands/elsabro/plan-milestone-gaps.md +20 -1
  16. package/commands/elsabro/plan.md +264 -36
  17. package/commands/elsabro/progress.md +203 -79
  18. package/commands/elsabro/quick.md +19 -0
  19. package/commands/elsabro/remove-phase.md +17 -0
  20. package/commands/elsabro/research-phase.md +18 -1
  21. package/commands/elsabro/resume-work.md +19 -0
  22. package/commands/elsabro/start.md +399 -98
  23. package/commands/elsabro/verify-work.md +138 -5
  24. package/hooks/confirm-destructive.sh +145 -0
  25. package/hooks/hooks-config.json +81 -0
  26. package/hooks/lint-check.sh +238 -0
  27. package/hooks/post-edit-test.sh +189 -0
  28. package/package.json +3 -2
  29. package/references/SYSTEM_INDEX.md +241 -0
  30. package/references/command-flow.md +352 -0
  31. package/references/enforcement-rules.md +331 -0
  32. package/references/error-contracts-tests.md +1171 -0
  33. package/references/error-contracts.md +3102 -0
  34. package/references/error-handling-instructions.md +26 -12
  35. package/references/parallel-worktrees.md +293 -0
  36. package/references/state-sync.md +381 -0
  37. package/references/task-dispatcher.md +388 -0
  38. package/references/tasks-integration.md +380 -0
  39. package/scripts/setup-parallel-worktrees.sh +319 -0
  40. package/skills/api-microservice.md +765 -0
  41. package/skills/api-setup.md +76 -3
  42. package/skills/auth-setup.md +46 -6
  43. package/skills/chrome-extension.md +584 -0
  44. package/skills/cicd-setup.md +1206 -0
  45. package/skills/cli-tool.md +884 -0
  46. package/skills/database-setup.md +41 -5
  47. package/skills/desktop-app.md +1351 -0
  48. package/skills/expo-app.md +35 -2
  49. package/skills/full-stack-app.md +543 -0
  50. package/skills/memory-update.md +207 -0
  51. package/skills/mobile-app.md +813 -0
  52. package/skills/nextjs-app.md +33 -2
  53. package/skills/payments-setup.md +76 -1
  54. package/skills/review.md +331 -0
  55. package/skills/saas-starter.md +639 -0
  56. package/skills/sentry-setup.md +41 -7
  57. package/skills/techdebt.md +289 -0
  58. package/skills/testing-setup.md +1218 -0
  59. package/skills/tutor.md +219 -0
  60. package/templates/.planning/notes/.gitkeep +0 -0
  61. package/templates/CLAUDE.md.template +48 -0
  62. package/templates/error-handling-config.json +79 -2
  63. package/templates/mistakes.md.template +52 -0
  64. package/templates/patterns.md.template +114 -0
@@ -13,22 +13,225 @@ allowed-tools:
13
13
  - TaskUpdate
14
14
  - TaskList
15
15
  - TaskGet
16
+ - AskUserQuestion
16
17
  - mcp__plugin_context7_context7__*
17
18
  argument-hint: "[número de fase]"
19
+ sync:
20
+ reads: [".elsabro/state.json", ".planning/*-PLAN.md"]
21
+ writes: [".elsabro/state.json", ".elsabro/context.md"]
22
+ phases: ["initializing", "exploring", "executing_wave_N", "verifying", "done"]
23
+ passes_context_to: ["verify-work"]
24
+ dispatcher:
25
+ exploration:
26
+ agents: [Explore, feature-dev:code-explorer, Plan]
27
+ model: haiku
28
+ parallel: true
29
+ min_agents: 3
30
+ implementation:
31
+ agents: [elsabro-executor, feature-dev:code-architect]
32
+ model: opus
33
+ parallel: true
34
+ min_agents: 2
35
+ verification:
36
+ agents: [pr-review-toolkit:code-reviewer, pr-review-toolkit:silent-failure-hunter, pr-review-toolkit:pr-test-analyzer]
37
+ model: opus
38
+ parallel: true
39
+ min_agents: 3
18
40
  ---
19
41
 
20
42
  # ELSABRO: Execute
21
43
 
44
+ <state_sync>
45
+ ## SINCRONIZACIÓN DE ESTADO (OBLIGATORIO)
46
+
47
+ **IMPORTAR**: Este comando DEBE seguir `/references/state-sync.md` y `/references/enforcement-rules.md`.
48
+
49
+ ### Al Iniciar (ANTES de cualquier operación)
50
+
51
+ ```javascript
52
+ // 1. Crear task de inicialización
53
+ TaskCreate({
54
+ subject: "Initialize execute command",
55
+ description: "Leer estado y preparar ejecución",
56
+ activeForm: "Inicializando..."
57
+ })
58
+ TaskUpdate(id, status: "in_progress")
59
+
60
+ // 2. Leer estado existente
61
+ const state = Read(".elsabro/state.json") || createInitialState();
62
+
63
+ // 3. Verificar flujo en progreso
64
+ if (state.current_flow && state.current_flow.command !== "execute") {
65
+ AskUserQuestion({
66
+ questions: [{
67
+ question: `Hay un flujo de "${state.current_flow.command}" en progreso. ¿Continuar ese o empezar execute?`,
68
+ header: "Flujo",
69
+ options: [
70
+ { label: "Continuar anterior", description: "Retomar " + state.current_flow.command },
71
+ { label: "Empezar execute", description: "Pausar anterior" }
72
+ ]
73
+ }]
74
+ });
75
+ }
76
+
77
+ // 4. Actualizar estado
78
+ state.current_flow = { command: "execute", phase: "initializing", started_at: new Date().toISOString() };
79
+ Write(".elsabro/state.json", JSON.stringify(state, null, 2));
80
+
81
+ // 5. Completar task de inicialización
82
+ TaskUpdate(id, status: "completed")
83
+ ```
84
+
85
+ ### Al Cambiar de Fase
86
+
87
+ ```javascript
88
+ // Antes de exploración
89
+ state.current_flow.phase = "exploring";
90
+ Write(".elsabro/state.json", JSON.stringify(state, null, 2));
91
+
92
+ // Antes de cada wave
93
+ state.current_flow.phase = "executing_wave_" + waveNumber;
94
+ Write(".elsabro/state.json", JSON.stringify(state, null, 2));
95
+
96
+ // Antes de verificación
97
+ state.current_flow.phase = "verifying";
98
+ Write(".elsabro/state.json", JSON.stringify(state, null, 2));
99
+ ```
100
+
101
+ ### Al Completar
102
+
103
+ ```javascript
104
+ // Registrar en historial
105
+ state.history.push({
106
+ command: "execute",
107
+ completed_at: new Date().toISOString(),
108
+ result: "completed_phase_" + phaseNumber,
109
+ artifact: null
110
+ });
111
+
112
+ // Pasar contexto a verify-work
113
+ state.context.changed_files = [...changedFiles];
114
+ state.context.commits = [...commitIds];
115
+ state.context.tests_added = [...testFiles];
116
+ state.context.phase_completed = phaseNumber;
117
+
118
+ // Limpiar flujo y sugerir siguiente
119
+ state.current_flow = null;
120
+ state.suggested_next = "verify-work";
121
+
122
+ Write(".elsabro/state.json", JSON.stringify(state, null, 2));
123
+
124
+ // Actualizar context.md legible
125
+ Write(".elsabro/context.md", generateHumanReadableContext(state));
126
+ ```
127
+ </state_sync>
128
+
22
129
  <objective>
23
130
  Ejecutar planes de una fase con:
24
131
  - **Sistema de Tasks para tracking real** de waves y dependencias
132
+ - **Dispatcher inteligente con selección automática de modelo** (ver @references/task-dispatcher.md)
133
+ - **Ejecución por subagentes en paralelo** según tipo de tarea
25
134
  - Investigación de patrones con Context7
26
135
  - TDD cuando sea apropiado
27
136
  - Commits atómicos por tarea
28
137
  - Verificación automática con agregador
29
138
  </objective>
30
139
 
140
+ <dispatcher_integration>
141
+ ## Selección Automática de Modelo
142
+
143
+ **REGLA CRÍTICA:** Cada tarea se ejecuta con el modelo óptimo para su tipo.
144
+
145
+ ```
146
+ ┌─────────────────────────────────────────────────────────────────────────┐
147
+ │ MODELO SEGÚN FASE │
148
+ ├─────────────────────────────────────────────────────────────────────────┤
149
+ │ FASE │ SUBAGENTES │ MODELO │
150
+ ├────────────────────┼────────────────────────────────────┼───────────────┤
151
+ │ Exploración │ Explore │ HAIKU │
152
+ │ (pre-ejecución) │ feature-dev:code-explorer │ HAIKU │
153
+ │ │ Plan │ HAIKU │
154
+ │ │ (3 en paralelo obligatorio) │ │
155
+ ├────────────────────┼────────────────────────────────────┼───────────────┤
156
+ │ Implementación │ elsabro-executor │ OPUS │
157
+ │ (waves) │ feature-dev:code-architect │ OPUS │
158
+ │ │ (2+ en paralelo por wave) │ │
159
+ ├────────────────────┼────────────────────────────────────┼───────────────┤
160
+ │ Verificación │ pr-review-toolkit:code-reviewer │ OPUS │
161
+ │ (post-ejecución) │ pr-review-toolkit:silent-... │ OPUS │
162
+ │ │ pr-review-toolkit:pr-test-... │ OPUS │
163
+ │ │ (3 en paralelo obligatorio) │ │
164
+ └────────────────────┴────────────────────────────────────┴───────────────┘
165
+ ```
166
+
167
+ ### Por qué esta distribución
168
+
169
+ - **HAIKU para exploración:** Solo lee y mapea, no necesita razonamiento profundo
170
+ - **OPUS para implementación:** Escribe código, necesita máxima calidad
171
+ - **OPUS para verificación:** Análisis profundo de bugs y edge cases
172
+ </dispatcher_integration>
173
+
31
174
  <process>
175
+ ## Paso 0: Exploración Pre-Ejecución (HAIKU x3 paralelo)
176
+
177
+ **OBLIGATORIO:** Antes de ejecutar, explorar el codebase para entender contexto.
178
+
179
+ ```javascript
180
+ // Crear tasks de exploración
181
+ TaskCreate({
182
+ subject: "Explore: Find related files",
183
+ description: "Buscar archivos relacionados con la fase",
184
+ activeForm: "Buscando archivos...",
185
+ metadata: { type: "exploration", model: "haiku" }
186
+ }) // → explore-files-id
187
+
188
+ TaskCreate({
189
+ subject: "Explore: Analyze patterns",
190
+ description: "Analizar patrones existentes en el codebase",
191
+ activeForm: "Analizando patrones...",
192
+ metadata: { type: "exploration", model: "haiku" }
193
+ }) // → explore-patterns-id
194
+
195
+ TaskCreate({
196
+ subject: "Explore: Map architecture",
197
+ description: "Mapear arquitectura del área afectada",
198
+ activeForm: "Mapeando arquitectura...",
199
+ metadata: { type: "exploration", model: "haiku" }
200
+ }) // → explore-arch-id
201
+
202
+ // Marcar todas como in_progress
203
+ TaskUpdate({ taskId: "explore-files-id", status: "in_progress" })
204
+ TaskUpdate({ taskId: "explore-patterns-id", status: "in_progress" })
205
+ TaskUpdate({ taskId: "explore-arch-id", status: "in_progress" })
206
+
207
+ // Lanzar 3 agentes HAIKU EN PARALELO (UN SOLO MENSAJE)
208
+ Task({
209
+ subagent_type: "Explore",
210
+ model: "haiku",
211
+ description: "Buscar archivos relacionados",
212
+ prompt: "Busca archivos relacionados con la fase [N]. Lista los 10 más relevantes."
213
+ }) |
214
+ Task({
215
+ subagent_type: "feature-dev:code-explorer",
216
+ model: "haiku",
217
+ description: "Analizar patrones",
218
+ prompt: "Analiza patrones de arquitectura en el área de la fase [N]."
219
+ }) |
220
+ Task({
221
+ subagent_type: "Plan",
222
+ model: "haiku",
223
+ description: "Mapear arquitectura",
224
+ prompt: "Mapea componentes y flujo de datos del área afectada."
225
+ })
226
+
227
+ // Marcar completed
228
+ TaskUpdate({ taskId: "explore-files-id", status: "completed" })
229
+ TaskUpdate({ taskId: "explore-patterns-id", status: "completed" })
230
+ TaskUpdate({ taskId: "explore-arch-id", status: "completed" })
231
+ ```
232
+
233
+ **Resultado:** Contexto del codebase capturado antes de modificar nada.
234
+
32
235
  ## Paso 1: Descubrir Planes
33
236
 
34
237
  ```bash
@@ -93,26 +296,64 @@ Para cada wave:
93
296
  TaskUpdate({ taskId: "wave-W-id", status: "in_progress" })
94
297
  ```
95
298
 
96
- ### Si hay múltiples planes en la wave → Paralelo
299
+ ### Si hay múltiples planes en la wave → Paralelo (OPUS)
97
300
  ```javascript
98
301
  // Marcar todos los planes como in_progress
99
302
  TaskUpdate({ taskId: "plan-A-id", status: "in_progress" })
100
303
  TaskUpdate({ taskId: "plan-B-id", status: "in_progress" })
101
304
  TaskUpdate({ taskId: "plan-C-id", status: "in_progress" })
102
305
 
103
- // Lanzar agentes en paralelo (UN SOLO MENSAJE)
104
- Task(elsabro-executor) para Plan A |
105
- Task(elsabro-executor) para Plan B |
106
- Task(elsabro-executor) para Plan C
306
+ // Lanzar agentes OPUS en paralelo (UN SOLO MENSAJE)
307
+ // MODELO: OPUS porque escriben código
308
+ Task({
309
+ subagent_type: "elsabro-executor",
310
+ model: "opus", // ← OPUS para implementación
311
+ description: "Ejecutar Plan A",
312
+ prompt: "Implementa el Plan A siguiendo TDD..."
313
+ }) |
314
+ Task({
315
+ subagent_type: "elsabro-executor",
316
+ model: "opus", // ← OPUS para implementación
317
+ description: "Ejecutar Plan B",
318
+ prompt: "Implementa el Plan B siguiendo TDD..."
319
+ }) |
320
+ Task({
321
+ subagent_type: "elsabro-executor",
322
+ model: "opus", // ← OPUS para implementación
323
+ description: "Ejecutar Plan C",
324
+ prompt: "Implementa el Plan C siguiendo TDD..."
325
+ })
107
326
 
108
327
  // Al completar cada plan
109
328
  TaskUpdate({ taskId: "plan-A-id", status: "completed" })
110
329
  ```
111
330
 
112
- ### Si solo hay un plan → Secuencial
331
+ ### Validación arquitectónica en paralelo (OPUS x2)
332
+ ```javascript
333
+ // Además de implementar, validar arquitectura en paralelo
334
+ Task({
335
+ subagent_type: "elsabro-executor",
336
+ model: "opus",
337
+ description: "Implementar cambios",
338
+ prompt: "..."
339
+ }) |
340
+ Task({
341
+ subagent_type: "feature-dev:code-architect",
342
+ model: "opus", // ← OPUS para decisiones arquitectónicas
343
+ description: "Validar arquitectura",
344
+ prompt: "Verifica que la implementación sigue los patrones del codebase..."
345
+ })
346
+ ```
347
+
348
+ ### Si solo hay un plan → Secuencial (OPUS)
113
349
  ```javascript
114
350
  TaskUpdate({ taskId: "plan-X-id", status: "in_progress" })
115
- Task(elsabro-executor) para Plan único
351
+ Task({
352
+ subagent_type: "elsabro-executor",
353
+ model: "opus", // ← OPUS porque escribe código
354
+ description: "Ejecutar plan único",
355
+ prompt: "..."
356
+ })
116
357
  TaskUpdate({ taskId: "plan-X-id", status: "completed" })
117
358
  ```
118
359
 
@@ -151,18 +392,53 @@ TaskUpdate({
151
392
  })
152
393
  ```
153
394
 
154
- ### 4.2 Ejecutar verificación en paralelo
395
+ ### 4.2 Ejecutar verificación en paralelo (OPUS x3)
396
+
397
+ **OBLIGATORIO:** Usar 3 agentes OPUS para verificación profunda.
398
+
155
399
  ```javascript
400
+ // Crear task adicional de seguridad
401
+ TaskCreate({
402
+ subject: "Verify Security & Edge Cases",
403
+ activeForm: "Verificando seguridad...",
404
+ metadata: { type: "verifier", area: "security", model: "opus" }
405
+ }) // → verify-security-id
406
+
407
+ // Actualizar agregador para esperar los 3
408
+ TaskUpdate({
409
+ taskId: "verify-aggregate-id",
410
+ addBlockedBy: ["verify-functional-id", "verify-quality-id", "verify-security-id"]
411
+ })
412
+
413
+ // Marcar todos como in_progress
156
414
  TaskUpdate({ taskId: "verify-functional-id", status: "in_progress" })
157
415
  TaskUpdate({ taskId: "verify-quality-id", status: "in_progress" })
158
-
159
- // Lanzar agentes verificadores en paralelo
160
- Task(elsabro-verifier): Verifica funcionalidad |
161
- Task(elsabro-verifier): Verifica calidad
416
+ TaskUpdate({ taskId: "verify-security-id", status: "in_progress" })
417
+
418
+ // Lanzar 3 agentes OPUS EN PARALELO (UN SOLO MENSAJE)
419
+ Task({
420
+ subagent_type: "pr-review-toolkit:code-reviewer",
421
+ model: "opus", // ← OPUS para análisis profundo
422
+ description: "Code review completo",
423
+ prompt: "Revisa los cambios buscando bugs, code smells, mejores prácticas..."
424
+ }) |
425
+ Task({
426
+ subagent_type: "pr-review-toolkit:silent-failure-hunter",
427
+ model: "opus", // ← OPUS para edge cases
428
+ description: "Buscar errores ocultos",
429
+ prompt: "Busca errores silenciosos, try/catch que ocultan errores, fallbacks problemáticos..."
430
+ }) |
431
+ Task({
432
+ subagent_type: "pr-review-toolkit:pr-test-analyzer",
433
+ model: "opus", // ← OPUS para análisis de tests
434
+ description: "Analizar cobertura de tests",
435
+ prompt: "Verifica que los tests cubren los cambios, busca casos críticos sin test..."
436
+ })
162
437
 
163
438
  // Marcar completed al terminar
164
439
  TaskUpdate({ taskId: "verify-functional-id", status: "completed" })
165
440
  TaskUpdate({ taskId: "verify-quality-id", status: "completed" })
441
+ TaskUpdate({ taskId: "verify-security-id", status: "completed" })
166
442
 
167
443
  // Agregador se desbloquea y genera reporte final
168
444
  TaskUpdate({ taskId: "verify-aggregate-id", status: "in_progress" })
@@ -312,74 +588,251 @@ TaskUpdate({
312
588
  ```
313
589
  </parallel_execution>
314
590
 
591
+ <worktrees_integration>
592
+ ## Integración con Worktrees Paralelos
593
+
594
+ **IMPORTAR**: En waves con múltiples agentes, usar worktrees para aislamiento.
595
+
596
+ ### Cuándo Usar Worktrees
597
+
598
+ - Profile "careful": SIEMPRE usar worktrees
599
+ - Más de 2 agentes en wave: Considerar worktrees
600
+ - Archivos compartidos entre agentes: OBLIGATORIO usar worktrees
601
+
602
+ ### Flujo con Worktrees
603
+
604
+ ```javascript
605
+ // Antes de ejecutar wave paralela
606
+ if (shouldUseWorktrees(wave, profile)) {
607
+ const agents = wave.plans.map(p => p.agent);
608
+
609
+ // Crear worktrees
610
+ Bash(`./scripts/setup-parallel-worktrees.sh create ${agents.join(' ')}`);
611
+
612
+ // Ejecutar agentes en sus worktrees
613
+ for (const agent of agents) {
614
+ Task({
615
+ subagent_type: agent,
616
+ prompt: `Trabaja en worktree: ../elsabro-worktrees/${agent}-wt/`
617
+ });
618
+ }
619
+
620
+ // Merge y cleanup al completar
621
+ Bash(`./scripts/setup-parallel-worktrees.sh complete ${agents.join(' ')}`);
622
+ }
623
+ ```
624
+
625
+ ### Resolución de Conflictos
626
+
627
+ Si hay conflictos en el merge:
628
+ 1. Pausar ejecución
629
+ 2. Mostrar conflictos al usuario
630
+ 3. Opciones: resolver manual, descartar branch, o abortar
631
+ </worktrees_integration>
632
+
315
633
  <error_handling>
316
- ## Manejo de Errores
634
+ ## Manejo de Errores en Ejecucion Paralela
635
+
636
+ **IMPORTAR**: Este comando DEBE seguir `/references/error-contracts.md`.
637
+
638
+ ### Inicializacion con Contratos
639
+
640
+ ```javascript
641
+ // Antes de cualquier wave, inicializar contratos
642
+ const registryValidator = new ContractRegistryValidator();
643
+ const sessionValidator = new ContractSessionValidator();
644
+ const timeoutHandler = new ContractTimeoutHandler();
645
+ const retryPolicy = new ContractRetryPolicy({
646
+ maxAttempts: 3,
647
+ baseDelayMs: 1000,
648
+ backoffMultiplier: 2
649
+ });
650
+ const errorAggregator = new ContractErrorAggregator("quorum");
651
+ const severityClassifier = new ContractSeverityClassifier();
652
+
653
+ // 1. Validar registry
654
+ const agentsNeeded = dispatcher.exploration.agents;
655
+ const batch = await registryValidator.validateBatch(agentsNeeded);
656
+ if (!batch.canProceed) {
657
+ return handleCriticalError("REGISTRY_MISSING", batch.details);
658
+ }
659
+
660
+ // 2. Validar sesion
661
+ const session = await sessionValidator.load();
662
+ if (!session.success) {
663
+ return handleCriticalError("SESSION_INVALID", session);
664
+ }
665
+ ```
666
+
667
+ ### Error Handling por Fase
317
668
 
318
- ### Política de Ejecución Paralela
669
+ #### Fase Exploracion (HAIKU x3)
670
+ ```javascript
671
+ // Policy: continue_all (exploracion es best-effort)
672
+ errorAggregator.setPolicy("continue_all");
319
673
 
320
- Este comando usa **policy: quorum** por defecto.
674
+ const results = await Promise.all([
675
+ executeWithRetry("explore-1", () => Task(Explore)),
676
+ executeWithRetry("explore-2", () => Task(CodeExplorer)),
677
+ executeWithRetry("explore-3", () => Task(Plan))
678
+ ]);
321
679
 
680
+ const summary = await errorAggregator.aggregate("exploration", results);
681
+ // continue_all: siempre continua, reporta al final
322
682
  ```
323
- ┌────────────────────────────────────────────────┐
324
- │ PARALLEL EXECUTION POLICY: quorum │
325
- ├────────────────────────────────────────────────┤
326
- │ Si >50% de agentes tienen éxito → continuar │
327
- │ Si ≤50% de agentes fallan → STOP │
328
- └────────────────────────────────────────────────┘
683
+
684
+ #### Fase Implementacion (OPUS x2 por wave)
685
+ ```javascript
686
+ // Policy: quorum (>50% debe tener exito)
687
+ errorAggregator.setPolicy("quorum");
688
+
689
+ for (const wave of waves) {
690
+ timeoutHandler.startTimeout(wave.id, 60 * 60 * 1000); // 60min por wave
691
+
692
+ const results = await Promise.all(
693
+ wave.plans.map(plan =>
694
+ executeWithRetry(plan.id, () => Task(elsabro-executor, plan))
695
+ )
696
+ );
697
+
698
+ const summary = await errorAggregator.aggregate(wave.id, results);
699
+
700
+ if (summary.decision === "STOP") {
701
+ // Quorum no alcanzado
702
+ await notifyUserImmediately({
703
+ severity: "CRITICAL",
704
+ message: `Wave ${wave.id} fallo: ${summary.reason}`,
705
+ options: ["retry", "debug", "abort"]
706
+ });
707
+ return;
708
+ }
709
+
710
+ timeoutHandler.completeTimeout(wave.id);
711
+ }
329
712
  ```
330
713
 
331
- ### Clasificación de Errores
714
+ #### Fase Verificacion (OPUS x3)
715
+ ```javascript
716
+ // Policy: fail_fast (verificacion debe pasar completa)
717
+ errorAggregator.setPolicy("fail_fast");
718
+
719
+ const verificationResults = await Promise.all([
720
+ executeWithRetry("verify-code", () => Task(CodeReviewer)),
721
+ executeWithRetry("verify-silent", () => Task(SilentFailureHunter)),
722
+ executeWithRetry("verify-tests", () => Task(TestAnalyzer))
723
+ ]);
724
+
725
+ const summary = await errorAggregator.aggregate("verification", verificationResults);
726
+
727
+ if (summary.decision === "STOP") {
728
+ // Cualquier fallo en verificacion es critico
729
+ await displayVerificationFailure(summary);
730
+ return;
731
+ }
732
+ ```
332
733
 
333
- | Severity | Emoji | Acción |
334
- |----------|-------|--------|
335
- | 🔴 CRITICAL | Parar | No puede continuar de ninguna forma |
336
- | 🟠 HIGH | Preguntar | Ofrecer opciones: fix/skip/abort |
337
- | 🟡 MEDIUM | Warning | Mostrar y continuar |
338
- | ⬜ LOW | Info | Log y continuar |
734
+ ### Escalamiento de Errores
339
735
 
340
- ### Si una tarea falla
736
+ ```
737
+ ┌─────────────────────────────────────────────────────────────────────┐
738
+ │ ESCALAMIENTO DE ERRORES │
739
+ ├─────────────────────────────────────────────────────────────────────┤
740
+ │ │
741
+ │ Error detectado │
742
+ │ ↓ │
743
+ │ SeverityClassifier.classify(error) │
744
+ │ ↓ │
745
+ │ ┌─────────────────────────────────────────────────────────────┐ │
746
+ │ │ CRITICAL: Notificar inmediatamente, STOP │ │
747
+ │ │ HIGH: Notificar, ofrecer opciones [fix/skip/abort] │ │
748
+ │ │ MEDIUM: Agregar a resumen, continuar │ │
749
+ │ │ LOW: Log para debugging, continuar │ │
750
+ │ └─────────────────────────────────────────────────────────────┘ │
751
+ │ │
752
+ └─────────────────────────────────────────────────────────────────────┘
753
+ ```
754
+
755
+ ### Retry Automatico con Backoff
341
756
 
757
+ ```javascript
758
+ async function executeWithRetry(operationId, operation) {
759
+ return await retryPolicy.executeWithRetry(
760
+ operationId,
761
+ operation,
762
+ {
763
+ onAttempt: (attempt) => {
764
+ console.log(`[RETRY] ${operationId}: Intento ${attempt}/3`);
765
+ },
766
+ onSuccess: (result, attempts) => {
767
+ if (attempts > 1) {
768
+ console.log(`[RECOVERED] ${operationId}: Exitoso en intento ${attempts}`);
769
+ }
770
+ },
771
+ onFailure: (error, attempts) => {
772
+ console.error(`[FAILED] ${operationId}: Fallo despues de ${attempts} intentos`);
773
+
774
+ // Clasificar para decidir siguiente accion
775
+ const classification = severityClassifier.classify(error.message);
776
+ if (classification.severity === "CRITICAL") {
777
+ throw new CriticalError(error, classification);
778
+ }
779
+ }
780
+ }
781
+ );
782
+ }
342
783
  ```
343
- 1. CLASIFICAR ERROR:
344
- - Tests fallan → HIGH
345
- - Build falla → HIGH
346
- - Dependencia falta → HIGH (auto-fixable)
347
- - Lint warnings → MEDIUM
348
- - File not found crítico → CRITICAL
349
784
 
350
- 2. APLICAR RETRY (si es transitorio):
351
- - Attempt 1: Ejecutar
352
- - Attempt 2: Esperar 1s, reintentar
353
- - Attempt 3: Esperar 2s, reintentar
354
- - Máximo 3 intentos, timeout total 2 min
785
+ ### Guardar Estado de Errores
355
786
 
356
- 3. SI RETRY FALLA Escalar según severidad
787
+ Al completar cada wave (exito o fallo):
357
788
 
358
- 4. MOSTRAR ERROR formateado:
359
- ╔══════════════════════════════════════════╗
360
- ║ 🟠 ERROR: TESTS_FAILED ║
361
- Severity: HIGH ║
362
- ╠══════════════════════════════════════════╣
363
- [Detalles del error] ║
364
- ╠══════════════════════════════════════════╣
365
- ║ [d] Debug [s] Skip [a] Abort ║
366
- ╚══════════════════════════════════════════╝
789
+ ```javascript
790
+ // Actualizar state.json con errores para recovery
791
+ state.errors = {
792
+ count: allErrors.length,
793
+ lastError: allErrors[allErrors.length - 1],
794
+ byWave: errorsByWave,
795
+ bySeverity: {
796
+ CRITICAL: criticalErrors,
797
+ HIGH: highErrors,
798
+ MEDIUM: mediumErrors,
799
+ LOW: lowErrors
800
+ }
801
+ };
802
+
803
+ state.parallelExecution = {
804
+ policy: currentPolicy,
805
+ activeAgents: [],
806
+ completedAgents: completedAgentIds,
807
+ failedAgents: failedAgentIds
808
+ };
809
+
810
+ await sessionValidator.save(state);
367
811
  ```
368
812
 
369
- ### Reglas de Desviación
813
+ ### Clasificacion de Errores (Referencia Rapida)
814
+
815
+ | Severity | Emoji | Accion |
816
+ |----------|-------|--------|
817
+ | CRITICAL | Parar | No puede continuar de ninguna forma |
818
+ | HIGH | Preguntar | Ofrecer opciones: fix/skip/abort |
819
+ | MEDIUM | Warning | Mostrar y continuar |
820
+ | LOW | Info | Log y continuar |
821
+
822
+ ### Reglas de Desviacion
370
823
 
371
- | Situación | Severity | Acción |
824
+ | Situacion | Severity | Accion |
372
825
  |-----------|----------|--------|
373
826
  | Bug que impide continuar | HIGH | Auto-fix (3 intentos) |
374
- | Falta validación crítica | HIGH | Auto-add |
827
+ | Falta validacion critica | HIGH | Auto-add |
375
828
  | Falta dependencia | HIGH | Auto-install |
376
- | Cambio arquitectónico | HIGH | CHECKPOINT |
829
+ | Cambio arquitectonico | HIGH | CHECKPOINT |
377
830
  | Tests fallan | HIGH | Debug o skip |
378
831
  | Lint warnings | MEDIUM | Continuar |
379
832
 
380
833
  ### Actualizar Estado con Tasks
381
834
 
382
- Después de errores, actualizar tanto SESSION-STATE.json como Tasks:
835
+ Despues de errores, actualizar tanto SESSION-STATE.json como Tasks:
383
836
 
384
837
  ```javascript
385
838
  // 1. Actualizar task con metadata de error
@@ -405,13 +858,13 @@ TaskCreate({
405
858
  metadata: { type: "bugfix", parentPlan: "plan-X-id" }
406
859
  }) // → bugfix-id
407
860
 
408
- // 3. Bloquear verificación hasta que bugfix complete
861
+ // 3. Bloquear verificacion hasta que bugfix complete
409
862
  TaskUpdate({
410
863
  taskId: "verify-aggregate-id",
411
864
  addBlockedBy: ["bugfix-id"]
412
865
  })
413
866
 
414
- // 4. También actualizar SESSION-STATE.json para compatibilidad
867
+ // 4. Tambien actualizar SESSION-STATE.json para compatibilidad
415
868
  ```
416
869
 
417
870
  ### Rollback de Estado con Tasks
@@ -435,7 +888,7 @@ TaskUpdate({ taskId: "plan-X-id", status: "completed" })
435
888
  // Listar todas las tasks
436
889
  TaskList()
437
890
 
438
- // Ver detalles de una task específica
891
+ // Ver detalles de una task especifica
439
892
  TaskGet({ taskId: "plan-X-id" })
440
893
  ```
441
894
  </error_handling>