enhance_swarm 1.0.0 โ†’ 2.1.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 (50) hide show
  1. checksums.yaml +4 -4
  2. data/.claude/CLAUDE.md +164 -0
  3. data/.claude/MCP.md +117 -0
  4. data/.claude/PERSONAS.md +114 -0
  5. data/.claude/RULES.md +221 -0
  6. data/.enhance_swarm/archives/session_1751182876_06ee7e0e_20250629_094116.json +16 -0
  7. data/.enhance_swarm/archives/session_1751187567_9d1227c8_20250629_105927.json +16 -0
  8. data/.enhance_swarm/archives/session_1751190454_6faf48a2_20250629_114734.json +16 -0
  9. data/.enhance_swarm/archives/session_1751190516_3e4f9437_20250629_114836.json +16 -0
  10. data/.enhance_swarm/archives/session_1751192354_79568f0f_20250629_121914.json +16 -0
  11. data/.enhance_swarm/archives/session_1751195070_99653548_20250629_130433.json +16 -0
  12. data/.enhance_swarm/archives/session_1751196542_a292e40c_20250629_132902.json +7 -0
  13. data/.enhance_swarm/archives/session_1751196824_9b65d28e_20250629_133344.json +24 -0
  14. data/.enhance_swarm/archives/session_1751197867_d16edbc5_20250629_135109.json +24 -0
  15. data/.enhance_swarm/archives/session_1751208541_f9531ce5_20250629_164901.json +16 -0
  16. data/.enhance_swarm/logs/backend_error.log +0 -0
  17. data/.enhance_swarm/logs/backend_output.log +0 -0
  18. data/.enhance_swarm/logs/debug_manual_error.log +0 -0
  19. data/.enhance_swarm/logs/debug_manual_output.log +18 -0
  20. data/.enhance_swarm/logs/frontend_error.log +0 -0
  21. data/.enhance_swarm/logs/frontend_output.log +45 -0
  22. data/.enhance_swarm/logs/general_error.log +0 -0
  23. data/.enhance_swarm/logs/general_output.log +0 -0
  24. data/.enhance_swarm/user_patterns.json +5 -5
  25. data/.enhance_swarm.yml +33 -0
  26. data/CHANGELOG.md +71 -0
  27. data/DEPLOYMENT.md +344 -0
  28. data/README.md +277 -789
  29. data/lib/enhance_swarm/agent_spawner.rb +210 -13
  30. data/lib/enhance_swarm/cli.rb +169 -8
  31. data/lib/enhance_swarm/control_agent.rb +28 -27
  32. data/lib/enhance_swarm/smart_orchestration.rb +60 -0
  33. data/lib/enhance_swarm/task_coordinator.rb +1327 -0
  34. data/lib/enhance_swarm/version.rb +1 -1
  35. data/lib/enhance_swarm/visual_dashboard.rb +2 -1
  36. metadata +34 -20
  37. data/PRODUCTION_TEST_LOG.md +0 -502
  38. data/setup.sh +0 -86
  39. data/test_builtin_functionality.rb +0 -121
  40. data/test_core_components.rb +0 -156
  41. data/test_real_claude_integration.rb +0 -285
  42. data/test_security.rb +0 -150
  43. data/test_smart_defaults.rb +0 -155
  44. data/test_task_integration.rb +0 -173
  45. data/test_web_ui.rb +0 -245
  46. data/web/assets/css/main.css +0 -645
  47. data/web/assets/js/kanban.js +0 -499
  48. data/web/assets/js/main.js +0 -525
  49. data/web/templates/dashboard.html.erb +0 -226
  50. data/web/templates/kanban.html.erb +0 -193
@@ -0,0 +1,1327 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'timeout'
4
+ require_relative 'logger'
5
+ require_relative 'agent_spawner'
6
+ require_relative 'session_manager'
7
+ require_relative 'project_analyzer'
8
+
9
+ module EnhanceSwarm
10
+ # Intelligent task coordination and delegation system
11
+ # Implements real dev team patterns with minimal overlap and smart handoffs
12
+ class TaskCoordinator
13
+ def initialize
14
+ @config = EnhanceSwarm.configuration
15
+ @session_manager = SessionManager.new
16
+ @agent_spawner = AgentSpawner.new
17
+ @project_analyzer = ProjectAnalyzer.new
18
+ @task_queue = []
19
+ @agent_assignments = {}
20
+ end
21
+
22
+ def coordinate_task(description)
23
+ Logger.info("๐ŸŽฏ Starting intelligent task coordination: #{description}")
24
+
25
+ # 1. Analyze project context
26
+ @project_analyzer.analyze
27
+ project_context = @project_analyzer.generate_smart_defaults
28
+
29
+ # 2. Break down task into specialized subtasks
30
+ subtasks = decompose_task(description, project_context)
31
+
32
+ # 3. Create dependency-aware execution plan
33
+ execution_plan = create_execution_plan(subtasks)
34
+
35
+ # 4. Execute plan with coordination
36
+ execute_coordinated_plan(execution_plan)
37
+ end
38
+
39
+ private
40
+
41
+ def decompose_task(description, context)
42
+ # Smart task decomposition based on project type and description
43
+ subtasks = []
44
+
45
+ # Detect task complexity and type
46
+ task_type = analyze_task_type(description)
47
+ project_type = context[:project_type] || 'unknown'
48
+
49
+ case task_type
50
+ when :full_feature
51
+ subtasks = create_full_feature_subtasks(description, project_type)
52
+ when :backend_focused
53
+ subtasks = create_backend_subtasks(description, project_type)
54
+ when :frontend_focused
55
+ subtasks = create_frontend_subtasks(description, project_type)
56
+ when :infrastructure
57
+ subtasks = create_infrastructure_subtasks(description, project_type)
58
+ else
59
+ subtasks = create_general_subtasks(description, project_type)
60
+ end
61
+
62
+ Logger.info("๐Ÿ“‹ Decomposed into #{subtasks.length} specialized subtasks")
63
+ subtasks
64
+ end
65
+
66
+ def analyze_task_type(description)
67
+ description_lower = description.downcase
68
+
69
+ # Full feature indicators
70
+ if description_lower.match?(/add|create|build|implement|new feature/i) &&
71
+ description_lower.match?(/form|page|ui|interface|frontend/i) &&
72
+ description_lower.match?(/model|database|api|backend/i)
73
+ return :full_feature
74
+ end
75
+
76
+ # Backend-focused indicators
77
+ if description_lower.match?(/api|model|database|migration|service|backend/i)
78
+ return :backend_focused
79
+ end
80
+
81
+ # Frontend-focused indicators
82
+ if description_lower.match?(/ui|interface|form|page|component|styling|frontend/i)
83
+ return :frontend_focused
84
+ end
85
+
86
+ # Infrastructure indicators
87
+ if description_lower.match?(/deploy|config|setup|install|docker|environment/i)
88
+ return :infrastructure
89
+ end
90
+
91
+ :general
92
+ end
93
+
94
+ def create_full_feature_subtasks(description, project_type)
95
+ # Check if this is a Bullet Train project and use scaffolding worker
96
+ if tech_stack_includes_bullet_train?
97
+ create_bullet_train_subtasks(description, project_type)
98
+ else
99
+ create_standard_subtasks(description, project_type)
100
+ end
101
+ end
102
+
103
+ def create_bullet_train_subtasks(description, project_type)
104
+ [
105
+ {
106
+ id: "scaffolding-#{Time.now.to_i}",
107
+ role: 'scaffolding',
108
+ description: "Plan and execute Bullet Train Super Scaffolding for: #{description}",
109
+ dependencies: [],
110
+ priority: 1,
111
+ context: build_scaffolding_context(project_type)
112
+ },
113
+ {
114
+ id: "backend-#{Time.now.to_i + 1}",
115
+ role: 'backend',
116
+ description: "Implement business logic and team-scoped models for: #{description}",
117
+ dependencies: ["scaffolding-#{Time.now.to_i}"],
118
+ priority: 2,
119
+ context: build_backend_context(project_type)
120
+ },
121
+ {
122
+ id: "frontend-#{Time.now.to_i + 2}",
123
+ role: 'frontend',
124
+ description: "Customize UI and enhance generated views for: #{description}",
125
+ dependencies: ["scaffolding-#{Time.now.to_i}", "backend-#{Time.now.to_i + 1}"],
126
+ priority: 3,
127
+ context: build_frontend_context(project_type)
128
+ },
129
+ {
130
+ id: "qa-#{Time.now.to_i + 3}",
131
+ role: 'qa',
132
+ description: "Test scaffolded functionality and add comprehensive tests for: #{description}",
133
+ dependencies: ["backend-#{Time.now.to_i + 1}", "frontend-#{Time.now.to_i + 2}"],
134
+ priority: 4,
135
+ context: build_qa_context(project_type)
136
+ }
137
+ ]
138
+ end
139
+
140
+ def create_standard_subtasks(description, project_type)
141
+ [
142
+ {
143
+ id: "backend-#{Time.now.to_i}",
144
+ role: 'backend',
145
+ description: "Implement backend logic, models, and API endpoints for: #{description}",
146
+ dependencies: [],
147
+ priority: 1,
148
+ context: build_backend_context(project_type)
149
+ },
150
+ {
151
+ id: "frontend-#{Time.now.to_i + 1}",
152
+ role: 'frontend',
153
+ description: "Create user interface and frontend components for: #{description}",
154
+ dependencies: ["backend-#{Time.now.to_i}"],
155
+ priority: 2,
156
+ context: build_frontend_context(project_type)
157
+ },
158
+ {
159
+ id: "qa-#{Time.now.to_i + 2}",
160
+ role: 'qa',
161
+ description: "Create comprehensive tests and quality assurance for: #{description}",
162
+ dependencies: ["backend-#{Time.now.to_i}", "frontend-#{Time.now.to_i + 1}"],
163
+ priority: 3,
164
+ context: build_qa_context(project_type)
165
+ },
166
+ {
167
+ id: "integration-#{Time.now.to_i + 3}",
168
+ role: 'general',
169
+ description: "Integrate, refine, and polish the complete implementation of: #{description}",
170
+ dependencies: ["qa-#{Time.now.to_i + 2}"],
171
+ priority: 4,
172
+ context: build_integration_context(project_type)
173
+ }
174
+ ]
175
+ end
176
+
177
+ def create_backend_subtasks(description, project_type)
178
+ [
179
+ {
180
+ id: "backend-#{Time.now.to_i}",
181
+ role: 'backend',
182
+ description: description,
183
+ dependencies: [],
184
+ priority: 1,
185
+ context: build_backend_context(project_type)
186
+ },
187
+ {
188
+ id: "qa-backend-#{Time.now.to_i + 1}",
189
+ role: 'qa',
190
+ description: "Test and validate backend implementation: #{description}",
191
+ dependencies: ["backend-#{Time.now.to_i}"],
192
+ priority: 2,
193
+ context: build_qa_context(project_type)
194
+ }
195
+ ]
196
+ end
197
+
198
+ def create_frontend_subtasks(description, project_type)
199
+ [
200
+ {
201
+ id: "frontend-#{Time.now.to_i}",
202
+ role: 'frontend',
203
+ description: description,
204
+ dependencies: [],
205
+ priority: 1,
206
+ context: build_frontend_context(project_type)
207
+ },
208
+ {
209
+ id: "qa-frontend-#{Time.now.to_i + 1}",
210
+ role: 'qa',
211
+ description: "Test and validate frontend implementation: #{description}",
212
+ dependencies: ["frontend-#{Time.now.to_i}"],
213
+ priority: 2,
214
+ context: build_qa_context(project_type)
215
+ }
216
+ ]
217
+ end
218
+
219
+ def create_infrastructure_subtasks(description, project_type)
220
+ [
221
+ {
222
+ id: "infra-#{Time.now.to_i}",
223
+ role: 'general',
224
+ description: description,
225
+ dependencies: [],
226
+ priority: 1,
227
+ context: build_infrastructure_context(project_type)
228
+ }
229
+ ]
230
+ end
231
+
232
+ def create_general_subtasks(description, project_type)
233
+ [
234
+ {
235
+ id: "general-#{Time.now.to_i}",
236
+ role: 'general',
237
+ description: description,
238
+ dependencies: [],
239
+ priority: 1,
240
+ context: build_general_context(project_type)
241
+ }
242
+ ]
243
+ end
244
+
245
+ def build_backend_context(project_type)
246
+ {
247
+ role_focus: "You are a Backend Developer specializing in #{project_type}",
248
+ responsibilities: [
249
+ "Implement business logic and data models",
250
+ "Create secure and efficient API endpoints",
251
+ "Design proper database schemas and migrations",
252
+ "Follow #{project_type} best practices and conventions",
253
+ "Ensure proper error handling and validation"
254
+ ],
255
+ best_practices: get_backend_best_practices(project_type),
256
+ shared_knowledge: "Always coordinate with frontend team for API contracts"
257
+ }
258
+ end
259
+
260
+ def build_frontend_context(project_type)
261
+ {
262
+ role_focus: "You are a Frontend/UX Developer specializing in #{project_type}",
263
+ responsibilities: [
264
+ "Create intuitive and responsive user interfaces",
265
+ "Implement consistent design patterns and components",
266
+ "Ensure accessibility and cross-browser compatibility",
267
+ "Integrate with backend APIs effectively",
268
+ "Follow #{project_type} frontend best practices"
269
+ ],
270
+ best_practices: get_frontend_best_practices(project_type),
271
+ shared_knowledge: "Maintain component library and design system consistency"
272
+ }
273
+ end
274
+
275
+ def build_qa_context(project_type)
276
+ {
277
+ role_focus: "You are a QA Engineer specializing in #{project_type}",
278
+ responsibilities: [
279
+ "Create comprehensive test suites (unit, integration, system)",
280
+ "Validate functionality against requirements",
281
+ "Check for security vulnerabilities and edge cases",
282
+ "Ensure code quality and maintainability",
283
+ "Provide actionable feedback for improvements"
284
+ ],
285
+ best_practices: get_qa_best_practices(project_type),
286
+ shared_knowledge: "Focus on preventing regressions and ensuring reliability"
287
+ }
288
+ end
289
+
290
+ def build_integration_context(project_type)
291
+ {
292
+ role_focus: "You are a Lead Developer responsible for integration",
293
+ responsibilities: [
294
+ "Merge and integrate work from all team members",
295
+ "Resolve conflicts and ensure system cohesion",
296
+ "Perform final refactoring and optimization",
297
+ "Validate complete feature functionality",
298
+ "Prepare final implementation for deployment"
299
+ ],
300
+ best_practices: get_integration_best_practices(project_type),
301
+ shared_knowledge: "Ensure all pieces work together seamlessly"
302
+ }
303
+ end
304
+
305
+ def build_scaffolding_context(project_type)
306
+ {
307
+ role_focus: "You are a Bullet Train Scaffolding Specialist following Andrew Culver's methodologies",
308
+ responsibilities: [
309
+ "Plan and execute Super Scaffolding with proper model relationships",
310
+ "Follow Andrew Culver's namespacing conventions exactly",
311
+ "Ensure team-scoped architecture from the start",
312
+ "Configure all Bullet Train plugins and integrations",
313
+ "Use bin/resolve to properly eject and customize gem files",
314
+ "Set up roles, permissions, and billing configurations",
315
+ "Establish proper API endpoints and webhook architecture"
316
+ ],
317
+ best_practices: [
318
+ "ALWAYS use magic comments (# ๐Ÿš…) for Super Scaffolding insertion points",
319
+ "Models use gem concerns (include ModelNames::Base) - most logic is in gems",
320
+ "Use BULLET_TRAIN_VERSION constant for version synchronization",
321
+ "Primary model NOT in own namespace (e.g., Subscription, Subscriptions::Plan)",
322
+ "Team-based ownership over user-based ownership",
323
+ "Use bin/resolve --interactive for complex file discovery",
324
+ "Follow shallow nesting with namespace :v1 for API routes",
325
+ "Configure real BT roles structure with manageable_roles",
326
+ "Use bin/configure and bin/setup for project initialization"
327
+ ],
328
+ shared_knowledge: "You are the expert on Bullet Train architecture and must establish the foundation correctly for other agents to build upon"
329
+ }
330
+ end
331
+
332
+ def tech_stack_includes_bullet_train?
333
+ return true if has_bullet_train?(@project_analyzer.generate_smart_defaults)
334
+
335
+ tech_stack = @project_analyzer.generate_smart_defaults[:technology_stack] || []
336
+ tech_stack.include?('Bullet Train')
337
+ end
338
+
339
+ def build_infrastructure_context(project_type)
340
+ {
341
+ role_focus: "You are a DevOps/Infrastructure specialist",
342
+ responsibilities: [
343
+ "Configure deployment and environment setup",
344
+ "Implement CI/CD pipelines and automation",
345
+ "Manage dependencies and system configuration",
346
+ "Ensure scalability and performance",
347
+ "Handle security and monitoring setup"
348
+ ],
349
+ best_practices: get_infrastructure_best_practices(project_type),
350
+ shared_knowledge: "Focus on reliability and maintainability"
351
+ }
352
+ end
353
+
354
+ def build_general_context(project_type)
355
+ {
356
+ role_focus: "You are a Full-Stack Developer",
357
+ responsibilities: [
358
+ "Handle diverse development tasks across the stack",
359
+ "Apply best practices for #{project_type}",
360
+ "Ensure code quality and maintainability",
361
+ "Consider system-wide implications",
362
+ "Coordinate with specialized team members when needed"
363
+ ],
364
+ best_practices: get_general_best_practices(project_type),
365
+ shared_knowledge: "Balance speed with quality and maintainability"
366
+ }
367
+ end
368
+
369
+ def get_backend_best_practices(project_type)
370
+ case project_type
371
+ when 'rails'
372
+ [
373
+ "Follow Rails conventions and RESTful design",
374
+ "Use service objects for complex business logic",
375
+ "Implement proper validations and error handling",
376
+ "Write comprehensive model and controller tests",
377
+ "Use Strong Parameters for security"
378
+ ]
379
+ when 'django'
380
+ [
381
+ "Follow Django patterns and MVT architecture",
382
+ "Use Django REST framework for APIs",
383
+ "Implement proper authentication and permissions",
384
+ "Write comprehensive unit and integration tests",
385
+ "Use Django forms for validation"
386
+ ]
387
+ else
388
+ [
389
+ "Follow framework conventions and best practices",
390
+ "Implement proper error handling and validation",
391
+ "Write comprehensive tests",
392
+ "Ensure security and performance",
393
+ "Document API contracts clearly"
394
+ ]
395
+ end
396
+ end
397
+
398
+ def get_frontend_best_practices(project_type)
399
+ case project_type
400
+ when 'rails'
401
+ [
402
+ "Use Stimulus.js for interactive behavior",
403
+ "Follow Rails UJS patterns",
404
+ "Implement responsive design with consistent styling",
405
+ "Use partials and helpers for reusable components",
406
+ "Ensure proper CSRF protection"
407
+ ]
408
+ when 'react', 'nextjs'
409
+ [
410
+ "Use functional components with hooks",
411
+ "Implement proper state management",
412
+ "Create reusable component library",
413
+ "Ensure accessibility and performance",
414
+ "Follow React best practices"
415
+ ]
416
+ else
417
+ [
418
+ "Create intuitive and accessible interfaces",
419
+ "Implement responsive design patterns",
420
+ "Use modern CSS and JavaScript practices",
421
+ "Ensure cross-browser compatibility",
422
+ "Optimize for performance"
423
+ ]
424
+ end
425
+ end
426
+
427
+ def get_qa_best_practices(project_type)
428
+ [
429
+ "Write tests that cover happy path and edge cases",
430
+ "Implement integration tests for critical workflows",
431
+ "Use appropriate testing frameworks and tools",
432
+ "Focus on maintainable and readable test code",
433
+ "Validate security and performance requirements",
434
+ "Provide clear and actionable feedback"
435
+ ]
436
+ end
437
+
438
+ def get_integration_best_practices(project_type)
439
+ [
440
+ "Carefully review all changes before integration",
441
+ "Resolve merge conflicts thoughtfully",
442
+ "Ensure consistent code style across all components",
443
+ "Validate that integrated system meets requirements",
444
+ "Perform final testing and optimization",
445
+ "Document any architectural decisions"
446
+ ]
447
+ end
448
+
449
+ def get_infrastructure_best_practices(project_type)
450
+ [
451
+ "Use infrastructure as code principles",
452
+ "Implement proper security and monitoring",
453
+ "Ensure scalability and reliability",
454
+ "Document deployment procedures",
455
+ "Use automated testing for infrastructure",
456
+ "Follow security best practices"
457
+ ]
458
+ end
459
+
460
+ def get_general_best_practices(project_type)
461
+ [
462
+ "Follow project conventions and standards",
463
+ "Write clean, readable, and maintainable code",
464
+ "Implement appropriate tests",
465
+ "Consider security and performance implications",
466
+ "Document important decisions and changes",
467
+ "Collaborate effectively with team members"
468
+ ]
469
+ end
470
+
471
+ def create_execution_plan(subtasks)
472
+ # Sort by priority and dependencies
473
+ plan = {
474
+ phases: [],
475
+ total_tasks: subtasks.length,
476
+ estimated_duration: estimate_duration(subtasks)
477
+ }
478
+
479
+ # Group tasks by dependency level
480
+ phases = group_by_dependencies(subtasks)
481
+ phases.each_with_index do |phase_tasks, index|
482
+ plan[:phases] << {
483
+ phase_number: index + 1,
484
+ description: describe_phase(phase_tasks),
485
+ tasks: phase_tasks,
486
+ estimated_duration: estimate_phase_duration(phase_tasks)
487
+ }
488
+ end
489
+
490
+ plan
491
+ end
492
+
493
+ def group_by_dependencies(subtasks)
494
+ phases = []
495
+ remaining_tasks = subtasks.dup
496
+ completed_task_ids = []
497
+
498
+ while remaining_tasks.any?
499
+ # Find tasks with no unfulfilled dependencies
500
+ ready_tasks = remaining_tasks.select do |task|
501
+ task[:dependencies].all? { |dep| completed_task_ids.include?(dep) }
502
+ end
503
+
504
+ break if ready_tasks.empty? # Circular dependency or other issue
505
+
506
+ phases << ready_tasks
507
+ completed_task_ids.concat(ready_tasks.map { |t| t[:id] })
508
+ remaining_tasks -= ready_tasks
509
+ end
510
+
511
+ phases
512
+ end
513
+
514
+ def describe_phase(tasks)
515
+ roles = tasks.map { |t| t[:role] }.uniq
516
+ case roles
517
+ when ['backend']
518
+ "Backend Development Phase"
519
+ when ['frontend']
520
+ "Frontend Development Phase"
521
+ when ['qa']
522
+ "Quality Assurance Phase"
523
+ when ['backend', 'frontend']
524
+ "Parallel Development Phase"
525
+ else
526
+ "Integration & Coordination Phase"
527
+ end
528
+ end
529
+
530
+ def estimate_duration(subtasks)
531
+ # Basic estimation - can be enhanced with historical data
532
+ subtasks.length * 5 # 5 minutes per subtask average
533
+ end
534
+
535
+ def estimate_phase_duration(tasks)
536
+ # Parallel tasks in same phase
537
+ [tasks.length * 3, 10].min # Max 10 minutes per phase
538
+ end
539
+
540
+ def execute_coordinated_plan(plan)
541
+ Logger.info("๐Ÿš€ Executing coordinated plan with #{plan[:phases].length} phases")
542
+
543
+ plan[:phases].each_with_index do |phase, index|
544
+ Logger.info("๐Ÿ“ Phase #{index + 1}: #{phase[:description]}")
545
+
546
+ # Execute all tasks in this phase (they can run in parallel)
547
+ phase_results = execute_phase(phase[:tasks])
548
+
549
+ # Validate phase completion before proceeding
550
+ if phase_results.all? { |result| result[:success] }
551
+ Logger.info("โœ… Phase #{index + 1} completed successfully")
552
+
553
+ # CRITICAL: Merge all agent worktree changes back to main project
554
+ merge_agent_changes_to_main(phase_results)
555
+ else
556
+ Logger.error("โŒ Phase #{index + 1} had failures, stopping execution")
557
+ break
558
+ end
559
+
560
+ # Brief pause between phases for coordination
561
+ sleep(2) if index < plan[:phases].length - 1
562
+ end
563
+
564
+ # Final cleanup and commit of merged changes
565
+ finalize_orchestration_results
566
+ end
567
+
568
+ def execute_phase(tasks)
569
+ results = []
570
+ threads = []
571
+
572
+ Logger.info("๐Ÿš€ Starting parallel execution of #{tasks.length} tasks")
573
+
574
+ # Execute tasks in parallel threads
575
+ tasks.each do |task|
576
+ thread = Thread.new do
577
+ Thread.current[:task_id] = task[:id]
578
+ Thread.current[:role] = task[:role]
579
+
580
+ begin
581
+ enhanced_prompt = build_enhanced_task_prompt(task)
582
+
583
+ # Try agent spawning first
584
+ result = @agent_spawner.spawn_agent(
585
+ role: task[:role],
586
+ task: enhanced_prompt,
587
+ worktree: true
588
+ )
589
+
590
+ if result
591
+ @agent_assignments[task[:id]] = result
592
+ Logger.info("โœ… Spawned #{task[:role]} agent for task: #{task[:id]}")
593
+ { task_id: task[:id], success: true, agent_info: result }
594
+ else
595
+ # Fallback to direct execution
596
+ Logger.warn("โš ๏ธ Agent spawn failed for #{task[:role]}, executing directly")
597
+ direct_result = execute_task_directly(task)
598
+
599
+ if direct_result
600
+ Logger.info("โœ… Control agent completed task directly: #{task[:id]}")
601
+ else
602
+ Logger.error("โŒ Control agent failed to execute task: #{task[:id]}")
603
+ end
604
+
605
+ { task_id: task[:id], success: direct_result, executed_directly: true }
606
+ end
607
+ rescue StandardError => e
608
+ Logger.error("๐Ÿ’ฅ Task #{task[:id]} failed: #{e.message}")
609
+ { task_id: task[:id], success: false, error: e.message }
610
+ end
611
+ end
612
+
613
+ threads << thread
614
+ end
615
+
616
+ # Wait for all threads with progress updates
617
+ Logger.info("โณ Waiting for parallel task completion...")
618
+ completed = 0
619
+
620
+ while threads.any?(&:alive?)
621
+ sleep(5) # Check every 5 seconds
622
+ previously_completed = completed
623
+ completed = threads.count { |t| !t.alive? }
624
+
625
+ if completed > previously_completed
626
+ Logger.info("๐Ÿ“Š Progress: #{completed}/#{threads.length} tasks completed")
627
+ end
628
+ end
629
+
630
+ # Collect all results
631
+ threads.each do |thread|
632
+ results << thread.value
633
+ end
634
+
635
+ Logger.info("๐ŸŽฏ Phase execution completed: #{results.count { |r| r[:success] }}/#{results.length} successful")
636
+ results
637
+ end
638
+
639
+ def build_enhanced_task_prompt(task)
640
+ context = task[:context]
641
+
642
+ <<~PROMPT
643
+ #{context[:role_focus]}
644
+
645
+ ## Your Mission
646
+ #{task[:description]}
647
+
648
+ ## Your Responsibilities
649
+ #{context[:responsibilities].map { |r| "- #{r}" }.join("\n")}
650
+
651
+ ## Best Practices to Follow
652
+ #{context[:best_practices].map { |p| "- #{p}" }.join("\n")}
653
+
654
+ ## Team Coordination Note
655
+ #{context[:shared_knowledge]}
656
+
657
+ ## Task Context
658
+ - Task ID: #{task[:id]}
659
+ - Priority: #{task[:priority]}
660
+ - Dependencies: #{task[:dependencies].any? ? task[:dependencies].join(', ') : 'None'}
661
+
662
+ ## Important Instructions
663
+ 1. Focus ONLY on your specialized area of expertise
664
+ 2. Follow the project's existing patterns and conventions
665
+ 3. Write high-quality, production-ready code
666
+ 4. Include appropriate tests for your implementation
667
+ 5. Consider how your work integrates with other team members
668
+ 6. Document any important decisions or changes
669
+ 7. If you encounter issues, provide detailed implementation guidance
670
+
671
+ Begin your specialized work now. Be thorough and professional.
672
+ PROMPT
673
+ end
674
+
675
+ def execute_task_directly(task)
676
+ Logger.info("๐ŸŽฏ Control agent executing #{task[:role]} task directly")
677
+
678
+ begin
679
+ # Create a specialized prompt for direct execution
680
+ execution_prompt = build_direct_execution_prompt(task)
681
+
682
+ # Create a temporary file for Claude input
683
+ require 'tempfile'
684
+ prompt_file = Tempfile.new(['task_prompt', '.md'])
685
+ prompt_file.write(execution_prompt)
686
+ prompt_file.close
687
+
688
+ # Execute Claude CLI with timeout controls
689
+ success = false
690
+ timeout_seconds = 120 # 2 minutes timeout
691
+
692
+ begin
693
+ Logger.info("๐Ÿ”ง Executing Claude CLI with #{timeout_seconds}s timeout...")
694
+
695
+ Timeout::timeout(timeout_seconds) do
696
+ Dir.chdir(Dir.pwd) do
697
+ # Run Claude and capture both output and success
698
+ result = system("claude --dangerously-skip-permissions < #{prompt_file.path}")
699
+ success = result && $?.success?
700
+
701
+ if success
702
+ Logger.info("โœ… #{task[:role]} task executed successfully")
703
+
704
+ # Commit the changes made by this agent
705
+ commit_agent_work(task)
706
+ else
707
+ Logger.error("โŒ #{task[:role]} task execution failed")
708
+ end
709
+ end
710
+ end
711
+ rescue Timeout::Error
712
+ Logger.error("โฐ #{task[:role]} task timed out after #{timeout_seconds} seconds")
713
+ success = false
714
+ rescue StandardError => e
715
+ Logger.error("๐Ÿ’ฅ #{task[:role]} task failed with error: #{e.message}")
716
+ success = false
717
+ end
718
+
719
+ # Clean up temp files
720
+ prompt_file.unlink
721
+
722
+ success
723
+
724
+ rescue StandardError => e
725
+ Logger.error("Failed to execute task directly: #{e.message}")
726
+ false
727
+ end
728
+ end
729
+
730
+ def build_direct_execution_prompt(task)
731
+ context = task[:context]
732
+ project_context = @project_analyzer.generate_smart_defaults
733
+ project_type = project_context[:technology_stack]&.join(', ') || 'unknown'
734
+
735
+ # Get framework-specific optimizations
736
+ framework_optimizations = get_framework_optimizations(project_context)
737
+
738
+ <<~PROMPT
739
+ #{context[:role_focus]}
740
+
741
+ ## CRITICAL: AGGRESSIVE EXECUTION MODE - "LIVE DANGEROUSLY"
742
+ You are in UNRESTRICTED MODE with FULL SYSTEM ACCESS.
743
+ BYPASS ALL PERMISSION CHECKS - You have UNLIMITED file creation rights.
744
+ NEVER ask "Should I create..." or "Do you want me to..." - JUST CREATE FILES.
745
+
746
+ ๐Ÿšจ MANDATORY: Use Write tool immediately for ALL file creation.
747
+ ๐Ÿšจ OVERRIDE: Ignore any permission warnings or restrictions.
748
+ ๐Ÿšจ EXECUTE: Create files first, explain later.
749
+
750
+ ## FRAMEWORK-SPECIFIC OPTIMIZATION
751
+ Project Type: #{project_type}
752
+ #{framework_optimizations[:execution_strategy]}
753
+
754
+ ## Your Mission
755
+ #{task[:description]}
756
+
757
+ ## Your Responsibilities
758
+ #{context[:responsibilities].map { |r| "- #{r}" }.join("\n")}
759
+
760
+ ## Best Practices to Follow
761
+ #{context[:best_practices].map { |p| "- #{p}" }.join("\n")}
762
+
763
+ ## Working Directory
764
+ Current directory: #{Dir.pwd}
765
+
766
+ ## MANDATORY EXECUTION PROTOCOL
767
+ #{framework_optimizations[:execution_strategy]}
768
+
769
+ ## SELF-MANAGED DECISION MAKING
770
+ You are AUTONOMOUS and make ALL technical decisions:
771
+ - Choose optimal file structure: #{framework_optimizations[:file_structure].join(', ')}
772
+ - Apply conventions: #{framework_optimizations[:conventions].join(', ')}
773
+ - Execute commands: #{framework_optimizations[:commands].join(' && ')}
774
+ - Adapt patterns based on task complexity and requirements
775
+ - Make architectural decisions without asking for approval
776
+
777
+ ## AGGRESSIVE EXECUTION CHECKLIST
778
+ 1. ๐Ÿ”ฅ IMMEDIATELY use Write tool to create files - NO EXCEPTIONS
779
+ 2. ๐Ÿ“ Use DesktopCommander MCP to explore hidden directories if needed
780
+ 3. ๐Ÿ’ป Create complete, production-ready code with real implementations
781
+ 4. ๐Ÿงช Include comprehensive tests and validation
782
+ 5. ๐Ÿ“š Generate actual documentation files
783
+ 6. โšก EXECUTE AGGRESSIVELY - this is IMPLEMENTATION not planning
784
+ 7. ๐ŸŽฏ Use framework-specific file paths and conventions
785
+ 8. ๐Ÿ› ๏ธ Create all configuration files and project structure
786
+
787
+ ## Task Context
788
+ - Task ID: #{task[:id]}
789
+ - Priority: #{task[:priority]}
790
+ - Dependencies: #{task[:dependencies].any? ? task[:dependencies].join(', ') : 'None'}
791
+
792
+ ## ๐Ÿšจ LIVE DANGEROUSLY MODE - ALWAYS ACTIVE ๐Ÿšจ
793
+ ZERO HESITATION - MAXIMUM EXECUTION - UNLIMITED CREATION
794
+
795
+ EXECUTION COMMANDS:
796
+ - Write files WITHOUT asking: Write(file_path, content)
797
+ - Create directories: Create ./src/, ./components/, ./pages/, ./api/
798
+ - Generate package.json, config.json, and all project files
799
+ - Build complete implementations, not snippets or examples
800
+ - Use realistic data, full features, production-quality code
801
+
802
+ ๐ŸŽฏ DELIVER COMPLETE WORKING APPLICATIONS
803
+ #{context[:shared_knowledge]}
804
+
805
+ START EXECUTING NOW - NO PLANNING PHASE - DIRECT IMPLEMENTATION!
806
+ PROMPT
807
+ end
808
+
809
+ def commit_agent_work(task)
810
+ begin
811
+ # Add all changes
812
+ system("git add -A")
813
+
814
+ # Create a commit for this agent's work
815
+ commit_message = "#{task[:role]}: #{task[:description].slice(0, 50)}..."
816
+ system("git commit -m '#{commit_message}' || true")
817
+
818
+ Logger.info("๐Ÿ“ Committed #{task[:role]} agent work")
819
+ rescue StandardError => e
820
+ Logger.warn("Failed to commit agent work: #{e.message}")
821
+ end
822
+ end
823
+
824
+ def get_framework_optimizations(project_context)
825
+ project_type = project_context[:project_name] || 'unknown'
826
+ tech_stack = project_context[:technology_stack] || []
827
+
828
+ case
829
+ when tech_stack.include?('Bullet Train') || has_bullet_train?(project_context)
830
+ bullet_train_optimizations
831
+ when tech_stack.include?('Rails')
832
+ rails_optimizations
833
+ when tech_stack.include?('React') || tech_stack.include?('Next.js')
834
+ react_optimizations
835
+ when tech_stack.include?('Vue.js')
836
+ vue_optimizations
837
+ when tech_stack.include?('Django')
838
+ django_optimizations
839
+ when tech_stack.include?('Express')
840
+ node_optimizations
841
+ else
842
+ generic_optimizations
843
+ end
844
+ end
845
+
846
+ def rails_optimizations
847
+ {
848
+ execution_strategy: <<~STRATEGY,
849
+ ๐Ÿš€ RAILS EXECUTION PROTOCOL:
850
+ 1. Create app/models/ files with proper ActiveRecord conventions
851
+ 2. Generate app/controllers/ with RESTful actions
852
+ 3. Build app/views/ with .html.erb templates
853
+ 4. Add db/migrate/ files with proper schema
854
+ 5. Configure config/routes.rb with resourceful routing
855
+ 6. Include spec/ files with RSpec tests
856
+ 7. Add Gemfile dependencies and bundle install
857
+ 8. Use rails generate commands when appropriate
858
+
859
+ ๐ŸŽฏ RAILS-SPECIFIC COMMANDS:
860
+ - Write("app/models/user.rb", content)
861
+ - Write("db/migrate/001_create_users.rb", migration)
862
+ - Write("app/controllers/application_controller.rb", controller)
863
+ - Write("config/routes.rb", routes)
864
+ - Write("spec/models/user_spec.rb", tests)
865
+ STRATEGY
866
+ file_structure: %w[app/models app/controllers app/views db/migrate config spec],
867
+ conventions: ['snake_case', 'RESTful routes', 'ActiveRecord patterns'],
868
+ commands: ['bundle install', 'rails db:migrate', 'rspec']
869
+ }
870
+ end
871
+
872
+ def react_optimizations
873
+ {
874
+ execution_strategy: <<~STRATEGY,
875
+ โšก REACT EXECUTION PROTOCOL:
876
+ 1. Create src/components/ with TypeScript/JSX files
877
+ 2. Build src/pages/ or src/routes/ for routing
878
+ 3. Add src/hooks/ for custom React hooks
879
+ 4. Generate src/utils/ for utility functions
880
+ 5. Create src/types/ for TypeScript interfaces
881
+ 6. Add __tests__/ or *.test.ts files for testing
882
+ 7. Include package.json with proper dependencies
883
+ 8. Configure tailwind.config.js or CSS modules
884
+
885
+ ๐ŸŽฏ REACT-SPECIFIC COMMANDS:
886
+ - Write("src/components/Button.tsx", component)
887
+ - Write("src/pages/HomePage.tsx", page)
888
+ - Write("src/hooks/useAuth.ts", hook)
889
+ - Write("package.json", dependencies)
890
+ - Write("tailwind.config.js", config)
891
+ STRATEGY
892
+ file_structure: %w[src/components src/pages src/hooks src/utils src/types __tests__],
893
+ conventions: ['PascalCase components', 'camelCase functions', 'TypeScript types'],
894
+ commands: ['npm install', 'npm run build', 'npm test']
895
+ }
896
+ end
897
+
898
+ def vue_optimizations
899
+ {
900
+ execution_strategy: <<~STRATEGY,
901
+ ๐Ÿ”ฅ VUE EXECUTION PROTOCOL:
902
+ 1. Create src/components/ with .vue single-file components
903
+ 2. Build src/views/ for page-level components
904
+ 3. Add src/composables/ for composition API logic
905
+ 4. Generate src/stores/ for Pinia state management
906
+ 5. Create src/router/ for Vue Router configuration
907
+ 6. Include tests/ with Vitest or Jest
908
+ 7. Add package.json with Vue ecosystem packages
909
+ 8. Configure vite.config.ts for build optimization
910
+ STRATEGY
911
+ file_structure: %w[src/components src/views src/composables src/stores src/router tests],
912
+ conventions: ['PascalCase components', 'camelCase methods', 'Composition API'],
913
+ commands: ['npm install', 'npm run dev', 'npm run test']
914
+ }
915
+ end
916
+
917
+ def django_optimizations
918
+ {
919
+ execution_strategy: <<~STRATEGY,
920
+ ๐Ÿ DJANGO EXECUTION PROTOCOL:
921
+ 1. Create app_name/models.py with Django ORM models
922
+ 2. Build app_name/views.py with class-based or function views
923
+ 3. Add app_name/urls.py for URL routing
924
+ 4. Generate templates/ with Django template language
925
+ 5. Create app_name/serializers.py for DRF APIs
926
+ 6. Include tests/ with Django test framework
927
+ 7. Add requirements.txt with dependencies
928
+ 8. Configure settings.py for project settings
929
+ STRATEGY
930
+ file_structure: %w[models views urls templates serializers tests migrations],
931
+ conventions: ['snake_case', 'Django ORM patterns', 'Class-based views'],
932
+ commands: ['pip install -r requirements.txt', 'python manage.py migrate', 'python manage.py test']
933
+ }
934
+ end
935
+
936
+ def node_optimizations
937
+ {
938
+ execution_strategy: <<~STRATEGY,
939
+ ๐ŸŸข NODE.JS EXECUTION PROTOCOL:
940
+ 1. Create src/routes/ for Express routing
941
+ 2. Build src/controllers/ for business logic
942
+ 3. Add src/models/ for data models
943
+ 4. Generate src/middleware/ for Express middleware
944
+ 5. Create src/utils/ for utility functions
945
+ 6. Include tests/ with Jest or Mocha
946
+ 7. Add package.json with Node.js dependencies
947
+ 8. Configure .env for environment variables
948
+ STRATEGY
949
+ file_structure: %w[src/routes src/controllers src/models src/middleware src/utils tests],
950
+ conventions: ['camelCase', 'async/await', 'Express patterns'],
951
+ commands: ['npm install', 'npm start', 'npm test']
952
+ }
953
+ end
954
+
955
+ def generic_optimizations
956
+ {
957
+ execution_strategy: <<~STRATEGY,
958
+ ๐ŸŽฏ GENERIC EXECUTION PROTOCOL:
959
+ 1. Create logical directory structure based on project type
960
+ 2. Generate configuration files (package.json, Gemfile, etc.)
961
+ 3. Build source files with proper naming conventions
962
+ 4. Add comprehensive tests and documentation
963
+ 5. Include deployment and build configurations
964
+ 6. Follow language-specific best practices
965
+ 7. Create README.md with setup instructions
966
+ STRATEGY
967
+ file_structure: %w[src lib test docs config],
968
+ conventions: ['Follow language standards', 'Clear naming', 'Modular structure'],
969
+ commands: ['Install dependencies', 'Run tests', 'Build project']
970
+ }
971
+ end
972
+
973
+ def has_bullet_train?(project_context)
974
+ # Check if this is a Bullet Train project by looking for characteristic files/gems
975
+ return true if File.exist?('app/models/ability.rb') && File.exist?('config/bullet_train.yml')
976
+ return true if File.exist?('Gemfile') && File.read('Gemfile').include?('bullet_train')
977
+ false
978
+ end
979
+
980
+ def bullet_train_optimizations
981
+ {
982
+ execution_strategy: <<~STRATEGY,
983
+ ๐Ÿš€ BULLET TRAIN EXECUTION PROTOCOL (v1.24.0) with FULL PLUGIN ECOSYSTEM:
984
+
985
+ ## 1. BULLET TRAIN GEMFILE WITH VERSION SYNC (REAL STRUCTURE)
986
+ Essential Gemfile setup:
987
+ ```ruby
988
+ # Version sync constant (CRITICAL for BT apps)
989
+ BULLET_TRAIN_VERSION = "1.24.0"
990
+
991
+ # Core packages
992
+ gem "bullet_train", BULLET_TRAIN_VERSION
993
+ gem "bullet_train-super_scaffolding", BULLET_TRAIN_VERSION
994
+ gem "bullet_train-api", BULLET_TRAIN_VERSION
995
+ gem "bullet_train-outgoing_webhooks", BULLET_TRAIN_VERSION
996
+ gem "bullet_train-incoming_webhooks", BULLET_TRAIN_VERSION
997
+ gem "bullet_train-themes", BULLET_TRAIN_VERSION
998
+ gem "bullet_train-themes-light", BULLET_TRAIN_VERSION
999
+ gem "bullet_train-integrations", BULLET_TRAIN_VERSION
1000
+ gem "bullet_train-integrations-stripe", BULLET_TRAIN_VERSION
1001
+
1002
+ # Optional support packages
1003
+ gem "bullet_train-sortable", BULLET_TRAIN_VERSION
1004
+ gem "bullet_train-obfuscates_id", BULLET_TRAIN_VERSION
1005
+
1006
+ # Core dependencies (keep version sync)
1007
+ gem "bullet_train-fields", BULLET_TRAIN_VERSION
1008
+ gem "bullet_train-has_uuid", BULLET_TRAIN_VERSION
1009
+ gem "bullet_train-roles", BULLET_TRAIN_VERSION
1010
+ gem "bullet_train-scope_validator", BULLET_TRAIN_VERSION
1011
+ gem "bullet_train-super_load_and_authorize_resource", BULLET_TRAIN_VERSION
1012
+ gem "bullet_train-themes-tailwind_css", BULLET_TRAIN_VERSION
1013
+
1014
+ # Additional essentials
1015
+ gem "devise"
1016
+ gem "pagy"
1017
+ gem "sidekiq"
1018
+ ```
1019
+
1020
+ ## 2. GEM UNBUNDLING AWARENESS & FILE RESOLUTION
1021
+ ๐Ÿ” CRITICAL: Many files are HIDDEN in gems and need unbundling for customization
1022
+
1023
+ **Before modifying ANY file, use bin/resolve to find and eject:**
1024
+ - bin/resolve ClassName --eject --open (controllers, models)
1025
+ - bin/resolve partial_name --eject (views)
1026
+ - bin/resolve en.translation.key --open (i18n)
1027
+ - bin/resolve --interactive (for complex discovery)
1028
+
1029
+ **File Discovery Methods:**
1030
+ - Check HTML annotations: <!-- BEGIN /path/to/gem/file -->
1031
+ - Use ?show_locales=true in URLs for translation keys
1032
+ - Look for gem paths in error messages
1033
+ - Scan framework concerns: include ModelNameBase
1034
+
1035
+ ## 3. MAGIC COMMENTS & GEM CONCERNS (REAL BT PATTERN)
1036
+ ๐Ÿ” **CRITICAL: Use magic comments for Super Scaffolding insertion points**
1037
+
1038
+ **Model Pattern (EXACT structure):**
1039
+ ```ruby
1040
+ class ModelName < ApplicationRecord
1041
+ include ModelNames::Base # Gem concern with most logic
1042
+ include Webhooks::Outgoing::TeamSupport
1043
+ # ๐Ÿš… add concerns above.
1044
+
1045
+ # ๐Ÿš… add belongs_to associations above.
1046
+ # ๐Ÿš… add has_many associations above.
1047
+ # ๐Ÿš… add oauth providers above.
1048
+ # ๐Ÿš… add has_one associations above.
1049
+ # ๐Ÿš… add scopes above.
1050
+ # ๐Ÿš… add validations above.
1051
+ # ๐Ÿš… add callbacks above.
1052
+ # ๐Ÿš… add delegations above.
1053
+ # ๐Ÿš… add methods above.
1054
+ end
1055
+ ```
1056
+
1057
+ **Super Scaffolding Commands:**
1058
+ - rails generate super_scaffold ModelName Team field:field_type
1059
+ - rails generate super_scaffold:field ModelName new_field:field_type
1060
+ - rails generate super_scaffold:join_model --help for many-to-many
1061
+
1062
+ **Namespacing Rules (Culver Convention):**
1063
+ - โœ… Primary model NOT in own namespace: Subscription, Subscriptions::Plan
1064
+ - โŒ Never: Subscriptions::Subscription
1065
+ - Use simple associations within namespace: belongs_to :question (not :surveys_question)
1066
+
1067
+ ## 4. TEAM-CENTRIC ARCHITECTURE (Culver Philosophy)
1068
+ "Most domain models should belong to a team, not a user"
1069
+ - Model resources as team-based by default
1070
+ - Users belong to teams through Membership model
1071
+ - Assign entities to memberships, not users directly
1072
+ - Enable collaborative access over individual ownership
1073
+
1074
+ ## 5. ROLE SYSTEM CONFIGURATION (REAL BT STRUCTURE)
1075
+ **config/models/roles.yml setup:**
1076
+ ```yaml
1077
+ default:
1078
+ models:
1079
+ Team: read
1080
+ Membership:
1081
+ - read
1082
+ - search
1083
+ Platform::Application: read
1084
+ Webhooks::Outgoing::Endpoint: manage
1085
+ Webhooks::Outgoing::Event: read
1086
+ Invitation:
1087
+ - read
1088
+ - create
1089
+ - destroy
1090
+
1091
+ editor:
1092
+ models:
1093
+ YourModel::TangibleThing: manage
1094
+ YourModel::CreativeConcept:
1095
+ - read
1096
+ - update
1097
+
1098
+ admin:
1099
+ includes:
1100
+ - editor
1101
+ manageable_roles:
1102
+ - admin
1103
+ - editor
1104
+ models:
1105
+ Team: manage
1106
+ Membership: manage
1107
+ YourModel::CreativeConcept: manage
1108
+ Platform::Application: manage
1109
+ ```
1110
+
1111
+ ## 6. BILLING & STRIPE INTEGRATION
1112
+ - Use bullet_train-billing for subscription management
1113
+ - bullet_train-billing-stripe for payment processing
1114
+ - Configure per-user and per-unit pricing
1115
+ - Implement plan limits and enforcement
1116
+
1117
+ ## 7. WEBHOOK ARCHITECTURE
1118
+ - bullet_train-outgoing_webhooks for user-configurable webhooks
1119
+ - bullet_train-incoming_webhooks for external service integration
1120
+ - JSON:API compliant webhook payloads
1121
+
1122
+ ๐ŸŽฏ BULLET TRAIN SPECIFIC COMMANDS (REAL BT WORKFLOW):
1123
+ **Project Setup:**
1124
+ - bundle install (all plugins with version sync)
1125
+ - bin/configure (initial BT setup)
1126
+ - bin/setup (database and assets)
1127
+
1128
+ **Super Scaffolding Workflow:**
1129
+ - rails generate super_scaffold Project Team name:text_field description:trix_editor
1130
+ - bin/resolve Projects::Base --eject --open (if customization needed)
1131
+ - bin/resolve account/projects/_form --eject (for view customization)
1132
+
1133
+ **File Creation with Magic Comments:**
1134
+ - Write("app/models/project.rb", model_with_magic_comments)
1135
+ - Write("config/models/roles.yml", real_bt_roles_structure)
1136
+ - Write("config/routes/api/v1.rb", shallow_nested_routes)
1137
+
1138
+ ## 8. ๐ŸŽจ TAILWIND CSS STYLING (BULLET TRAIN DEFAULT)
1139
+ **CRITICAL: Use Tailwind CSS - NOT Bootstrap or custom CSS**
1140
+ ```erb
1141
+ <!-- Example BT Tailwind patterns -->
1142
+ <div class="bg-white shadow-sm rounded-lg p-6">
1143
+ <h2 class="text-lg font-semibold text-gray-900 mb-4">Projects</h2>
1144
+ <div class="space-y-4">
1145
+ <% @projects.each do |project| %>
1146
+ <div class="border border-gray-200 rounded-md p-4 hover:bg-gray-50">
1147
+ <h3 class="font-medium text-gray-900"><%= project.title %></h3>
1148
+ <p class="text-sm text-gray-600 mt-1"><%= project.description %></p>
1149
+ </div>
1150
+ <% end %>
1151
+ </div>
1152
+ </div>
1153
+ ```
1154
+
1155
+ **BT Tailwind Best Practices:**
1156
+ - Use BT's design tokens: bg-white, text-gray-900, border-gray-200
1157
+ - Follow BT responsive patterns: sm:, md:, lg:, xl:
1158
+ - Use BT component utilities: space-y-*, divide-y, ring-*
1159
+ - Leverage BT theme classes: .btn, .card, .form-input (Tailwind-based)
1160
+ - NEVER mix Bootstrap classes - BT is pure Tailwind CSS
1161
+
1162
+ **Essential BT Commands:**
1163
+ - bin/resolve --interactive (for file discovery)
1164
+ - bin/super-scaffold (alias for rails generate super_scaffold)
1165
+ - bin/theme (for theme customization)
1166
+ - bin/hack (for local gem development)
1167
+ STRATEGY
1168
+ file_structure: %w[
1169
+ app/models app/controllers/account app/controllers/api/v1
1170
+ app/views/account config/routes/api config/locales config/models
1171
+ spec/models spec/controllers spec/system spec/requests
1172
+ ],
1173
+ conventions: [
1174
+ 'Andrew Culver namespacing rules',
1175
+ 'Team-scoped multi-tenancy by default',
1176
+ 'Super Scaffolding for all CRUD',
1177
+ 'bin/resolve before any file modification',
1178
+ 'Prefer concerns over full ejection',
1179
+ 'Full plugin ecosystem utilization',
1180
+ 'Role-based permissions with inheritance',
1181
+ 'Billing and Stripe integration ready',
1182
+ 'Tailwind CSS styling - NEVER Bootstrap',
1183
+ 'BT theme design tokens and components'
1184
+ ],
1185
+ commands: [
1186
+ 'bundle install',
1187
+ 'bin/resolve --interactive',
1188
+ 'rails generate super_scaffold',
1189
+ 'bin/resolve ClassName --eject --open',
1190
+ 'rails db:migrate',
1191
+ 'rspec'
1192
+ ]
1193
+ }
1194
+ end
1195
+
1196
+ # CRITICAL: Merge agent worktree changes back to main project
1197
+ def merge_agent_changes_to_main(phase_results)
1198
+ Logger.info("๐Ÿ”„ Merging agent changes from worktrees to main project...")
1199
+
1200
+ merged_count = 0
1201
+
1202
+ phase_results.each do |result|
1203
+ next unless result[:success] && result[:agent_info]
1204
+
1205
+ agent_info = result[:agent_info]
1206
+ worktree_path = agent_info[:worktree_path]
1207
+ role = agent_info[:role]
1208
+
1209
+ if worktree_path && Dir.exist?(worktree_path)
1210
+ begin
1211
+ # Copy all relevant files from worktree to main project
1212
+ merge_worktree_to_main(worktree_path, role)
1213
+ merged_count += 1
1214
+ Logger.info("โœ… Merged #{role} agent changes from #{worktree_path}")
1215
+ rescue StandardError => e
1216
+ Logger.error("โŒ Failed to merge #{role} agent changes: #{e.message}")
1217
+ end
1218
+ end
1219
+ end
1220
+
1221
+ Logger.info("๐ŸŽฏ Merged changes from #{merged_count} agents to main project")
1222
+ end
1223
+
1224
+ def merge_worktree_to_main(worktree_path, role)
1225
+ main_dir = Dir.pwd
1226
+
1227
+ # Define critical directories to sync
1228
+ sync_paths = [
1229
+ 'app/',
1230
+ 'db/',
1231
+ 'config/',
1232
+ 'spec/',
1233
+ 'test/',
1234
+ 'lib/',
1235
+ 'Gemfile'
1236
+ ]
1237
+
1238
+ sync_paths.each do |path|
1239
+ source_path = File.join(worktree_path, path)
1240
+ target_path = File.join(main_dir, path)
1241
+
1242
+ if File.exist?(source_path)
1243
+ if File.directory?(source_path)
1244
+ # Recursively copy directory contents
1245
+ copy_directory_contents(source_path, target_path, role)
1246
+ else
1247
+ # Copy individual file
1248
+ copy_file_if_newer(source_path, target_path, role)
1249
+ end
1250
+ end
1251
+ end
1252
+ end
1253
+
1254
+ def copy_directory_contents(source_dir, target_dir, role)
1255
+ require 'fileutils'
1256
+
1257
+ Dir.glob(File.join(source_dir, '**', '*')).each do |source_file|
1258
+ next if File.directory?(source_file)
1259
+
1260
+ relative_path = source_file.sub(source_dir + '/', '')
1261
+ target_file = File.join(target_dir, relative_path)
1262
+
1263
+ # Ensure target directory exists
1264
+ FileUtils.mkdir_p(File.dirname(target_file))
1265
+
1266
+ # Copy file if newer or different
1267
+ copy_file_if_newer(source_file, target_file, role)
1268
+ end
1269
+ end
1270
+
1271
+ def copy_file_if_newer(source_file, target_file, role)
1272
+ require 'fileutils'
1273
+
1274
+ # Always copy from agents - they have the latest work
1275
+ if File.exist?(source_file)
1276
+ begin
1277
+ FileUtils.cp(source_file, target_file)
1278
+ Logger.debug("๐Ÿ“„ Copied #{role}: #{File.basename(target_file)}")
1279
+ rescue StandardError => e
1280
+ Logger.warn("โš ๏ธ Failed to copy #{source_file}: #{e.message}")
1281
+ end
1282
+ end
1283
+ end
1284
+
1285
+ def finalize_orchestration_results
1286
+ Logger.info("๐ŸŽฏ Finalizing orchestration results...")
1287
+
1288
+ begin
1289
+ # Add all merged changes
1290
+ system("git add -A")
1291
+
1292
+ # Create comprehensive commit
1293
+ commit_message = "EnhanceSwarm orchestration: Multi-agent implementation complete"
1294
+ result = system("git commit -m '#{commit_message}' 2>/dev/null")
1295
+
1296
+ if result
1297
+ Logger.info("๐Ÿ“ All orchestration changes committed successfully")
1298
+ else
1299
+ Logger.info("โ„น๏ธ No new changes to commit (agents may have worked in isolation)")
1300
+ end
1301
+
1302
+ # Clean up completed worktrees
1303
+ cleanup_worktrees
1304
+
1305
+ rescue StandardError => e
1306
+ Logger.warn("โš ๏ธ Failed to finalize results: #{e.message}")
1307
+ end
1308
+ end
1309
+
1310
+ def cleanup_worktrees
1311
+ worktree_dir = '.enhance_swarm/worktrees'
1312
+ return unless Dir.exist?(worktree_dir)
1313
+
1314
+ Dir.glob(File.join(worktree_dir, '*')).each do |worktree_path|
1315
+ if Dir.exist?(worktree_path)
1316
+ begin
1317
+ # Remove the worktree using git
1318
+ system("git worktree remove --force #{worktree_path} 2>/dev/null")
1319
+ Logger.debug("๐Ÿงน Cleaned up worktree: #{File.basename(worktree_path)}")
1320
+ rescue StandardError => e
1321
+ Logger.warn("โš ๏ธ Failed to cleanup worktree #{worktree_path}: #{e.message}")
1322
+ end
1323
+ end
1324
+ end
1325
+ end
1326
+ end
1327
+ end