Class: EnhanceSwarm::SmartDefaults

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/enhance_swarm/smart_defaults.rb

Constant Summary collapse

DEFAULT_SETTINGS_FILE =
'.enhance_swarm/smart_defaults.yml'
USER_PATTERNS_FILE =
'.enhance_swarm/user_patterns.json'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSmartDefaults

Returns a new instance of SmartDefaults.



14
15
16
17
18
19
# File 'lib/enhance_swarm/smart_defaults.rb', line 14

def initialize
  @settings = load_settings
  @user_patterns = load_user_patterns
  @project_context = analyze_project_context
  ensure_settings_directory
end

Class Method Details

.auto_cleanup_if_neededObject



695
696
697
# File 'lib/enhance_swarm/smart_defaults.rb', line 695

def auto_cleanup_if_needed
  instance.auto_cleanup_if_needed
end

.auto_retry_with_backoff(*args, &block) ⇒ Object



687
688
689
# File 'lib/enhance_swarm/smart_defaults.rb', line 687

def auto_retry_with_backoff(*args, &block)
  instance.auto_retry_with_backoff(*args, &block)
end

.get_suggestions(context = {}) ⇒ Object



703
704
705
# File 'lib/enhance_swarm/smart_defaults.rb', line 703

def get_suggestions(context = {})
  instance.suggest_next_actions(context)
end

.instanceObject



675
676
677
# File 'lib/enhance_swarm/smart_defaults.rb', line 675

def instance
  @instance ||= new
end

.learn_from_action(*args) ⇒ Object



699
700
701
# File 'lib/enhance_swarm/smart_defaults.rb', line 699

def learn_from_action(*args)
  instance.learn_from_action(*args)
end

.suggest_configurationObject



683
684
685
# File 'lib/enhance_swarm/smart_defaults.rb', line 683

def suggest_configuration
  instance.suggest_configuration
end

.suggest_next_actions(*args) ⇒ Object



691
692
693
# File 'lib/enhance_swarm/smart_defaults.rb', line 691

def suggest_next_actions(*args)
  instance.suggest_next_actions(*args)
end

.suggest_role_for_task(*args) ⇒ Object



679
680
681
# File 'lib/enhance_swarm/smart_defaults.rb', line 679

def suggest_role_for_task(*args)
  instance.suggest_role_for_task(*args)
end

Instance Method Details

#auto_cleanup_if_neededObject

Auto-cleanup stale resources



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/enhance_swarm/smart_defaults.rb', line 144

def auto_cleanup_if_needed
  cleanup_actions = []
  
  # Check for stale worktrees (older than 1 day)
  stale_worktrees = find_stale_worktrees
  if stale_worktrees.count > 3
    cleanup_actions << proc do
      CleanupManager.cleanup_stale_worktrees
      Logger.info("Auto-cleaned #{stale_worktrees.count} stale worktrees")
    end
  end
  
  # Check for old communication files (older than 7 days)
  old_comm_files = find_old_communication_files
  if old_comm_files.count > 20
    cleanup_actions << proc do
      AgentCommunicator.instance.cleanup_old_messages(7)
      Logger.info("Auto-cleaned #{old_comm_files.count} old communication files")
    end
  end
  
  # Check for old notification history (older than 14 days)
  if notification_history_size > 100
    cleanup_actions << proc do
      NotificationManager.instance.clear_history
      Logger.info("Auto-cleaned notification history")
    end
  end
  
  # Execute cleanup actions
  cleanup_actions.each(&:call)
  
  cleanup_actions.count
end

#auto_retry_with_backoff(operation, max_retries: 3, base_delay: 1) ⇒ Object

Auto-retry with intelligent backoff



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/enhance_swarm/smart_defaults.rb', line 72

def auto_retry_with_backoff(operation, max_retries: 3, base_delay: 1)
  attempt = 0
  last_error = nil
  
  loop do
    attempt += 1
    
    begin
      result = yield
      
      # Record successful pattern
      record_success_pattern(operation, attempt)
      return result
      
    rescue StandardError => e
      last_error = e
      
      if attempt >= max_retries
        record_failure_pattern(operation, attempt, e)
        raise e
      end
      
      # Calculate exponential backoff with jitter
      delay = base_delay * (2 ** (attempt - 1)) + rand(0.5)
      delay = [delay, 30].min # Cap at 30 seconds
      
      Logger.info("Retry #{attempt}/#{max_retries} for #{operation} in #{delay.round(1)}s: #{e.message}")
      sleep(delay)
    end
  end
end

#learn_from_action(action_type, details = {}) ⇒ Object

Learn from user actions and update patterns



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/enhance_swarm/smart_defaults.rb', line 180

def learn_from_action(action_type, details = {})
  @user_patterns['actions'] ||= {}
  @user_patterns['actions'][action_type] ||= {
    'count' => 0,
    'last_used' => nil,
    'success_rate' => 1.0,
    'preferences' => {}
  }
  
  action_data = @user_patterns['actions'][action_type]
  action_data['count'] += 1
  action_data['last_used'] = Time.now.iso8601
  
  # Update preferences based on details
  details.each do |key, value|
    action_data['preferences'][key.to_s] ||= {}
    action_data['preferences'][key.to_s][value.to_s] ||= 0
    action_data['preferences'][key.to_s][value.to_s] += 1
  end
  
  save_user_patterns
end

#suggest_commands_for_context(context = {}) ⇒ Object

Get context-aware command suggestions



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/enhance_swarm/smart_defaults.rb', line 204

def suggest_commands_for_context(context = {})
  suggestions = []
  
  # Based on current directory contents
  if File.exist?('package.json')
    suggestions << 'npm test' if context[:changed_files]&.any? { |f| f.end_with?('.js', '.ts') }
    suggestions << 'npm run build' if context[:action] == 'deploy'
  end
  
  if File.exist?('Gemfile')
    suggestions << 'bundle exec rspec' if context[:changed_files]&.any? { |f| f.end_with?('.rb') }
    suggestions << 'bundle exec rubocop' if context[:action] == 'lint'
  end
  
  # Based on git status
  if context[:git_status]
    if context[:git_status][:modified_files] && context[:git_status][:modified_files] > 0
      suggestions << 'enhance-swarm review'
    end
    
    if context[:git_status][:untracked_files] && context[:git_status][:untracked_files] > 0
      suggestions << 'git add .'
    end
  end
  
  # Based on user patterns
  frequent_commands.each { |cmd| suggestions << cmd }
  
  suggestions.uniq
end

#suggest_concurrency_settingsObject

Auto-detect optimal concurrency settings



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/enhance_swarm/smart_defaults.rb', line 236

def suggest_concurrency_settings
  # Base on system resources
  cpu_cores = detect_cpu_cores
  available_memory_gb = detect_available_memory
  
  # Conservative defaults
  max_agents = [cpu_cores / 2, 4].min
  max_agents = [max_agents, 2].max # At least 2
  
  # Adjust based on memory
  if available_memory_gb < 4
    max_agents = [max_agents, 2].min
  elsif available_memory_gb > 16
    max_agents = [max_agents + 2, 8].min
  end
  
  {
    max_concurrent_agents: max_agents,
    monitor_interval: max_agents > 4 ? 15 : 30,
    timeout_multiplier: available_memory_gb < 8 ? 1.5 : 1.0
  }
end

#suggest_configurationObject

Suggest optimal configuration based on project type



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/enhance_swarm/smart_defaults.rb', line 51

def suggest_configuration
  config = {}
  
  # Detect project type and suggest stack
  project_type = detect_project_type
  config[:project_type] = project_type
  config[:technology_stack] = suggest_technology_stack(project_type)
  
  # Suggest commands based on project files
  config[:commands] = suggest_commands(project_type)
  
  # Suggest orchestration settings
  config[:orchestration] = suggest_orchestration_settings
  
  # Add MCP tool suggestions
  config[:mcp_tools] = suggest_mcp_tools(project_type)
  
  config
end

#suggest_next_actions(current_context = {}) ⇒ Object

Suggest next actions based on current state



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/enhance_swarm/smart_defaults.rb', line 105

def suggest_next_actions(current_context = {})
  suggestions = []
  
  # Check for common issues and suggest fixes
  if stale_worktrees_detected?
    suggestions << {
      action: 'cleanup',
      command: 'enhance-swarm cleanup --all',
      reason: 'Stale worktrees detected',
      priority: :medium
    }
  end
  
  if pending_agent_messages?
    suggestions << {
      action: 'communicate',
      command: 'enhance-swarm communicate --interactive',
      reason: 'Pending agent messages need responses',
      priority: :high
    }
  end
  
  # Suggest based on project state
  if tests_need_running?
    suggestions << {
      action: 'test',
      command: determine_test_command,
      reason: 'Code changes detected, tests should be run',
      priority: :medium
    }
  end
  
  # Suggest based on user patterns
  time_based_suggestions.each { |suggestion| suggestions << suggestion }
  
  suggestions.sort_by { |s| priority_weight(s[:priority]) }.reverse
end

#suggest_role_for_task(task_description) ⇒ Object

Detect optimal role for a given task



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/enhance_swarm/smart_defaults.rb', line 22

def suggest_role_for_task(task_description)
  task_lower = task_description.downcase
  
  # Check for explicit role keywords
  role_keywords = {
    'backend' => %w[api server database model migration schema endpoint route controller service auth jwt],
    'frontend' => %w[ui ux component view page template css html javascript react vue angular design layout],
    'qa' => %w[test testing spec unit integration e2e selenium cypress jest rspec quality assurance bug],
    'ux' => %w[design user experience wireframe mockup prototype accessibility usability flow journey]
  }
  
  # Calculate keyword matches for each role
  role_scores = role_keywords.transform_values do |keywords|
    keywords.count { |keyword| task_lower.include?(keyword) }
  end
  
  # Add context from user patterns
  if @user_patterns['role_preferences']
    @user_patterns['role_preferences'].each do |role, weight|
      role_scores[role] = (role_scores[role] || 0) + weight.to_f
    end
  end
  
  # Return the role with highest score, or 'general' if tied
  best_role = role_scores.max_by { |_, score| score }
  best_role && best_role[1] > 0 ? best_role[0] : 'general'
end