Class: Aidp::Harness::UserInterface

Inherits:
Object
  • Object
show all
Includes:
MessageDisplay
Defined in:
lib/aidp/harness/user_interface.rb

Overview

Handles user interaction and feedback collection

Constant Summary

Constants included from MessageDisplay

MessageDisplay::COLOR_MAP, MessageDisplay::CRITICAL_TYPES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from MessageDisplay

#display_message, included, #message_display_prompt, #quiet_mode?

Constructor Details

#initialize(prompt: TTY::Prompt.new) ⇒ UserInterface

Returns a new instance of UserInterface.



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/aidp/harness/user_interface.rb', line 15

def initialize(prompt: TTY::Prompt.new)
  @input_history = []
  @file_selection_enabled = false
  @prompt = prompt
  @cursor = TTY::Cursor
  @control_mutex = Mutex.new
  @pause_requested = false
  @stop_requested = false
  @resume_requested = false
  @control_interface_enabled = false
  @control_thread = nil
end

Instance Attribute Details

#auto_confirm_defaultsObject (readonly)

Expose for testability



13
14
15
# File 'lib/aidp/harness/user_interface.rb', line 13

def auto_confirm_defaults
  @auto_confirm_defaults
end

#file_selection_enabledObject (readonly)

Expose for testability



13
14
15
# File 'lib/aidp/harness/user_interface.rb', line 13

def file_selection_enabled
  @file_selection_enabled
end

#show_help_automaticallyObject (readonly)

Expose for testability



13
14
15
# File 'lib/aidp/harness/user_interface.rb', line 13

def show_help_automatically
  @show_help_automatically
end

#verbose_modeObject (readonly)

Expose for testability



13
14
15
# File 'lib/aidp/harness/user_interface.rb', line 13

def verbose_mode
  @verbose_mode
end

Instance Method Details

#advanced_file_selection(max_files, _search_options) ⇒ Object

Get advanced file selection from user



1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
# File 'lib/aidp/harness/user_interface.rb', line 1618

def advanced_file_selection(max_files, _search_options)
  loop do
    input = @prompt.ask("Select file (0-#{max_files}, -1=refine, p=preview, h=help): ")

    if input.nil? || input.strip.empty?
      display_message("Please enter a selection.", type: :error)
      next
    end

    input = input.strip.downcase

    # Handle special commands
    case input
    when "h", "help"
      show_file_selection_help
      next
    when "p", "preview"
      display_message("💡 Select a file number first, then use 'p' to preview it.", type: :info)
      next
    end

    begin
      selection = input.to_i
      if selection == 0
        return nil # Cancel
      elsif selection == -1
        return -1 # Refine search
      elsif selection.between?(1, max_files)
        return selection - 1 # Convert to 0-based index
      else
        display_message("Please enter a number between 0 and #{max_files}, or use -1, p, h.", type: :error)
      end
    rescue ArgumentError
      display_message("Please enter a valid number or command (0-#{max_files}, -1, p, h).", type: :error)
    end
  end
end

#apply_preferences(preferences) ⇒ Object

Apply user preferences



1893
1894
1895
1896
1897
1898
# File 'lib/aidp/harness/user_interface.rb', line 1893

def apply_preferences(preferences)
  @auto_confirm_defaults = preferences[:auto_confirm_defaults] || false
  @show_help_automatically = preferences[:show_help_automatically] || false
  @verbose_mode = preferences[:verbose_mode] != false
  @file_selection_enabled = preferences[:file_browsing_enabled] != false
end

#build_glob_pattern(base_path, search_options) ⇒ Object

Build glob pattern for file search



1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
# File 'lib/aidp/harness/user_interface.rb', line 1444

def build_glob_pattern(base_path, search_options)
  if search_options[:extensions].any?
    # Search for specific extensions
    extensions = search_options[:extensions].join(",")
    File.join(base_path, "**", "*{#{extensions}}")
  else
    # Search for all files
    File.join(base_path, "**", "*")
  end
end

#check_control_inputObject

Check for control input during execution



2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
# File 'lib/aidp/harness/user_interface.rb', line 2220

def check_control_input
  return unless @control_interface_enabled

  if pause_requested?
    handle_pause_state
  elsif stop_requested?
    handle_stop_state
    return :stop
  elsif resume_requested?
    handle_resume_state
    return :resume
  end

  nil
end

#choice(message, options, default: nil) ⇒ Object

Get choice from multiple options



1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
# File 'lib/aidp/harness/user_interface.rb', line 1741

def choice(message, options, default: nil)
  display_message("\n#{message}", type: :info)
  options.each_with_index do |option, index|
    marker = (default && index == default) ? " (default)" : ""
    display_message("  #{index + 1}. #{option}#{marker}", type: :info)
  end

  loop do
    input = @prompt.ask("Your choice (1-#{options.size}): ")

    if input.nil? || input.strip.empty?
      return default if default
      display_message("Please make a selection.", type: :error)
      next
    end

    begin
      choice = input.strip.to_i
      if choice.between?(1, options.size)
        return choice - 1 # Convert to 0-based index
      else
        display_message("Please enter a number between 1 and #{options.size}.", type: :error)
      end
    rescue ArgumentError
      display_message("Please enter a valid number.", type: :error)
    end
  end
end

#choice_response(options, default_value, required) ⇒ Object

Get choice response with enhanced validation



617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
# File 'lib/aidp/harness/user_interface.rb', line 617

def choice_response(options, default_value, required)
  return nil if options.nil? || options.empty?

  display_message("\n   Available options:", type: :info)
  options.each_with_index do |option, index|
    marker = (default_value && option == default_value) ? " (default)" : ""
    display_message("     #{index + 1}. #{option}#{marker}", type: :info)
  end

  loop do
    prompt = "Your choice (1-#{options.size})"
    prompt += " (default: #{default_value})" if default_value
    prompt += required ? ": " : " (optional): "

    input = @prompt.ask(prompt)

    if input.nil? || input.strip.empty?
      if default_value
        return default_value
      elsif required
        display_message("❌ Please make a selection.", type: :error)
        next
      else
        return nil
      end
    end

    # Enhanced validation for choice
    validation_result = validate_input_type(input.strip, "choice", {choices: options})

    unless validation_result[:valid]
      display_validation_error(validation_result, "choice")
      next
    end

    # Check for warnings
    if display_validation_warnings(validation_result)
      next
    end

    # Parse the choice
    choice = input.strip
    if choice.match?(/\A\d+\z/)
      return options[choice.to_i - 1]
    else
      return choice
    end
  end
end

#clear_control_requestsObject

Clear all control requests



2084
2085
2086
2087
2088
2089
2090
# File 'lib/aidp/harness/user_interface.rb', line 2084

def clear_control_requests
  @control_mutex.synchronize do
    @pause_requested = false
    @stop_requested = false
    @resume_requested = false
  end
end

#clear_historyObject

Clear input history



1792
1793
1794
# File 'lib/aidp/harness/user_interface.rb', line 1792

def clear_history
  @input_history.clear
end

#clear_progressObject

Clear progress message



1776
1777
1778
# File 'lib/aidp/harness/user_interface.rb', line 1776

def clear_progress
  print_to_stderr(@cursor.clear_line, @cursor.column(1))
end

#collect_batch_feedback(questions) ⇒ Object

Batch collect feedback for multiple simple questions



1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
# File 'lib/aidp/harness/user_interface.rb', line 1966

def collect_batch_feedback(questions)
  responses = {}

  display_message("\n📝 Quick Feedback Collection:", type: :info)
  display_message("=" * 35, type: :muted)

  questions.each_with_index do |question_data, index|
    question_number = index + 1
    question_text = question_data[:question]
    question_type = question_data[:type] || "text"
    default_value = question_data[:default]
    required = question_data[:required] != false

    display_message("\n#{question_number}. #{question_text}", type: :info)

    response = quick_feedback(question_text, {
      type: question_type,
      default: default_value,
      required: required,
      options: question_data[:options]
    })

    responses["question_#{question_number}"] = response
  end

  display_message("\n✅ Batch feedback collected.", type: :success)
  responses
end

#collect_feedback(questions, context = nil) ⇒ Object

Collect user feedback for a list of questions



69
70
71
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
103
104
105
# File 'lib/aidp/harness/user_interface.rb', line 69

def collect_feedback(questions, context = nil)
  responses = {}

  # Display context if provided
  if context
    display_feedback_context(context)
  end

  # Display question presentation header
  display_question_presentation_header(questions, context)

  # Process questions with advanced presentation
  questions.each_with_index do |question_data, index|
    question_number = question_data[:number] || (index + 1)

    # Display question with advanced formatting
    display_numbered_question(question_data, question_number, index + 1, questions.length)

    # Get user response based on question type
    response = question_response(question_data, question_number)

    # Validate response if required
    if question_data[:required] != false && (response.nil? || response.to_s.strip.empty?)
      display_message("❌ This question is required. Please provide a response.", type: :error)
      redo
    end

    responses["question_#{question_number}"] = response

    # Show progress indicator
    display_question_progress(index + 1, questions.length)
  end

  # Display completion summary
  display_question_completion_summary(responses, questions)
  responses
end

#collect_feedback_with_preferences(questions, context = nil, preferences = {}) ⇒ Object

Get feedback with preferences



1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
# File 'lib/aidp/harness/user_interface.rb', line 1913

def collect_feedback_with_preferences(questions, context = nil, preferences = {})
  # Apply preferences
  apply_preferences(preferences)

  # Track seen question types
  seen_types = Set.new

  # Show help if needed
  if should_show_help?(questions.first&.dig(:type), seen_types)
    show_help
    display_message("\nPress Enter to continue...", type: :info)
    @prompt.keypress("Press any key to continue...")
  end

  # Display question summary if verbose
  if @verbose_mode
    display_question_summary(questions)
    display_message("\nPress Enter to start answering questions...", type: :info)
    @prompt.keypress("Press any key to continue...")
  end

  # Collect feedback
  responses = collect_feedback(questions, context)

  # Mark question types as seen
  questions.each do |question_data|
    mark_question_type_seen(question_data[:type] || "text", seen_types)
  end

  responses
end

#confirmation(message, default: true) ⇒ Object

Get confirmation from user



1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
# File 'lib/aidp/harness/user_interface.rb', line 1717

def confirmation(message, default: true)
  default_text = default ? "Y/n" : "y/N"
  prompt = "#{message} [#{default_text}]: "

  loop do
    input = @prompt.ask(prompt)

    if input.nil? || input.strip.empty?
      return default
    end

    response = input.strip.downcase
    case response
    when "y", "yes"
      return true
    when "n", "no"
      return false
    else
      display_message("Please enter 'y' or 'n'.", type: :error)
    end
  end
end

#confirmation_response(default_value, required) ⇒ Object

Get confirmation response with enhanced validation



668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# File 'lib/aidp/harness/user_interface.rb', line 668

def confirmation_response(default_value, required)
  default = default_value.nil? || default_value
  default_text = default ? "Y/n" : "y/N"
  prompt = "Your response [#{default_text}]"
  prompt += required ? ": " : " (optional): "

  loop do
    input = @prompt.ask(prompt)

    if input.nil? || input.strip.empty?
      return default
    end

    # Enhanced validation for boolean
    validation_result = validate_input_type(input.strip, "boolean")

    unless validation_result[:valid]
      display_validation_error(validation_result, "boolean")
      next
    end

    # Check for warnings
    if display_validation_warnings(validation_result)
      next
    end

    response = input.strip.downcase
    case response
    when "y", "yes", "true", "1"
      return true
    when "n", "no", "false", "0"
      return false
    end
  end
end

#control_interface_loopObject

Control interface main loop



2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
# File 'lib/aidp/harness/user_interface.rb', line 2187

def control_interface_loop
  loop do
    input = @prompt.ask("Control> ")

    case input&.strip&.downcase
    when "p", "pause"
      request_pause
    when "r", "resume"
      request_resume
    when "s", "stop"
      request_stop
    when "h", "help"
      show_control_help
    when "q", "quit"
      stop_control_interface
      break
    when ""
      # Empty input, continue
      next
    else
      display_message("❌ Invalid command. Type 'h' for help.", type: :error)
    end
  rescue Interrupt
    display_message("\n🛑 Control interface interrupted. Stopping...", type: :error)
    request_stop
    break
  rescue => e
    display_message("❌ Control interface error: #{e.message}", type: :error)
    display_message("   Type 'h' for help or 'q' to quit.", type: :info)
  end
end

#control_interface_with_timeout(timeout_seconds = 30) ⇒ Object

Control interface with timeout



2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
# File 'lib/aidp/harness/user_interface.rb', line 2334

def control_interface_with_timeout(timeout_seconds = 30)
  return unless @control_interface_enabled

  start_time = Time.now

  loop do
    if pause_requested?
      handle_pause_state
    elsif stop_requested?
      handle_stop_state
      break
    elsif resume_requested?
      handle_resume_state
      break
    elsif Time.now - start_time > timeout_seconds
      display_message("\n⏰ Control interface timeout reached. Continuing execution...", type: :warning)
      break
    else
      # Periodic check for user confirmation
      sleep(0.1)
    end
  end
end

#control_statusObject

Get control status



2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
# File 'lib/aidp/harness/user_interface.rb', line 2250

def control_status
  @control_mutex.synchronize do
    {
      enabled: !!@control_interface_enabled,
      pause_requested: !!@pause_requested,
      stop_requested: !!@stop_requested,
      resume_requested: !!@resume_requested,
      control_thread_alive: !!@control_thread&.alive?
    }
  end
end

#determine_search_paths(search_options) ⇒ Object

Determine search paths based on options



1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
# File 'lib/aidp/harness/user_interface.rb', line 1424

def determine_search_paths(search_options)
  if search_options[:directories].any?
    search_options[:directories]
  else
    [
      ".",
      "lib",
      "spec",
      "app",
      "src",
      "docs",
      "templates",
      "config",
      "test",
      "tests"
    ]
  end
end

#disable_control_interfaceObject

Disable control interface



2243
2244
2245
2246
2247
# File 'lib/aidp/harness/user_interface.rb', line 2243

def disable_control_interface
  @control_interface_enabled = false
  stop_control_interface
  display_message("🎮 Control interface disabled", type: :info)
end

#display_advanced_file_menu(files, search_options) ⇒ Object

Display advanced file selection menu



1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
# File 'lib/aidp/harness/user_interface.rb', line 1541

def display_advanced_file_menu(files, search_options)
  display_message("\n📁 Available files:", type: :info)
  display_message("Search: #{search_options[:term]} | Extensions: #{search_options[:extensions].join(", ")} | Directories: #{search_options[:directories].join(", ")}", type: :info)
  display_message("-" * 80, type: :muted)

  files.each_with_index do |file, index|
    file_info = get_file_info(file)
    display_message("  #{index + 1}. #{file_info[:display_name]}", type: :info)
    display_message("     📄 #{file_info[:size]} | 📅 #{file_info[:modified]} | 🏷️  #{file_info[:type]}", type: :muted)
  end

  display_message("\nOptions:", type: :info)
  display_message("  0. Cancel", type: :info)
  display_message("  -1. Refine search", type: :info)
  display_message("  p. Preview selected file", type: :info)
  display_message("  h. Show help", type: :info)
end

#display_context_summary(context) ⇒ Object

Display context summary



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/aidp/harness/user_interface.rb', line 173

def display_context_summary(context)
  display_message("\n📋 Context Summary:", type: :info)

  if context[:type]
    display_message("  Type: #{context[:type]}", type: :info)
  end

  if context[:urgency]
    urgency_emojis = {
      "high" => "🔴",
      "medium" => "🟡",
      "low" => "🟢"
    }
    urgency_emoji = urgency_emojis[context[:urgency]] || "ℹ️"
    display_message("  Urgency: #{urgency_emoji} #{context[:urgency].capitalize}", type: :info)
  end

  if context[:description]
    display_message("  Description: #{context[:description]}", type: :info)
  end
end

#display_control_statusObject

Display control status



2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
# File 'lib/aidp/harness/user_interface.rb', line 2263

def display_control_status
  status = control_status

  display_message("\n🎮 Control Interface Status", type: :info)
  display_message("=" * 40, type: :muted)
  display_message("Enabled: #{status[:enabled] ? "✅ Yes" : "❌ No"}", type: :info)
  display_message("Pause Requested: #{status[:pause_requested] ? "⏸️  Yes" : "▶️  No"}", type: :info)
  display_message("Stop Requested: #{status[:stop_requested] ? "🛑 Yes" : "▶️  No"}", type: :info)
  display_message("Resume Requested: #{status[:resume_requested] ? "▶️  Yes" : "⏸️  No"}", type: :info)
  display_message("Control Thread: #{status[:control_thread_alive] ? "🟢 Active" : "🔴 Inactive"}", type: :info)
  display_message("=" * 40, type: :muted)
end

#display_feedback_context(context) ⇒ Object

Display feedback context



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
# File 'lib/aidp/harness/user_interface.rb', line 108

def display_feedback_context(context)
  display_message("\n📋 Context:", type: :highlight)
  display_message("-" * 30, type: :muted)

  if context[:type]
    display_message("Type: #{context[:type]}", type: :info)
  end

  if context[:urgency]
    urgency_emojis = {
      "high" => "🔴",
      "medium" => "🟡",
      "low" => "🟢"
    }
    urgency_emoji = urgency_emojis[context[:urgency]] || "ℹ️"
    display_message("Urgency: #{urgency_emoji} #{context[:urgency].capitalize}", type: :info)
  end

  if context[:description]
    display_message("Description: #{context[:description]}", type: :info)
  end

  if context[:agent_output]
    display_message("\nAgent Output:", type: :info)
    display_message(context[:agent_output], type: :info)
  end
end

#display_numbered_question(question_data, question_number, _current_index, total_questions) ⇒ Object

Display numbered question with advanced formatting



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/aidp/harness/user_interface.rb', line 231

def display_numbered_question(question_data, question_number, _current_index, total_questions)
  question_text = question_data[:question]
  question_type = question_data[:type] || "text"
  expected_input = question_data[:expected_input] || "text"
  options = question_data[:options]
  default_value = question_data[:default]
  required = question_data[:required] != false

  # Display question header
  display_message("\n" + "=" * 60, type: :muted)
  display_message("📝 Question #{question_number} of #{total_questions}", type: :highlight)
  display_message("=" * 60, type: :muted)

  # Display question text with formatting
  display_question_text(question_text, question_type)

  # Display question metadata
  (question_type, expected_input, options, default_value, required)

  # Display question instructions
  display_question_instructions(question_type, options, default_value, required)

  display_message("\n" + "-" * 60, type: :muted)
end

#display_question_completion_summary(responses, questions) ⇒ Object

Display question completion summary



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/aidp/harness/user_interface.rb', line 400

def display_question_completion_summary(responses, questions)
  display_message("\n" + "=" * 60, type: :muted)
  display_message("✅ Question Completion Summary", type: :success)
  display_message("=" * 60, type: :muted)

  # Show completion statistics
  total_questions = questions.length
  answered_questions = responses.values.count { |v| !v.nil? && !v.to_s.strip.empty? }
  skipped_questions = total_questions - answered_questions

  display_message("📊 Statistics:", type: :info)
  display_message("  Total questions: #{total_questions}", type: :info)
  display_message("  Answered: #{answered_questions}", type: :info)
  display_message("  Skipped: #{skipped_questions}", type: :info)
  display_message("  Completion rate: #{(answered_questions.to_f / total_questions * 100).round(1)}%", type: :info)

  # Show response summary
  display_message("\n📝 Response Summary:", type: :info)
  responses.each do |key, value|
    question_number = key.gsub("question_", "")
    if value.nil? || value.to_s.strip.empty?
      display_message("  #{question_number}. [Skipped]", type: :muted)
    else
      display_value = (value.to_s.length > 50) ? "#{value.to_s[0..47]}..." : value.to_s
      display_message("  #{question_number}. #{display_value}", type: :info)
    end
  end

  display_message("\n🚀 Continuing execution...", type: :success)
end

#display_question_instructions(question_type, options, default_value, required) ⇒ Object

Display question instructions



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/aidp/harness/user_interface.rb', line 302

def display_question_instructions(question_type, options, default_value, required)
  display_message("\n💡 Instructions:", type: :info)

  case question_type
  when "text"
    display_message("  • Enter your text response", type: :info)
    display_message("  • Use @ for file selection if needed", type: :info)
    display_message("  • Press Enter when done", type: :info)
  when "choice"
    display_message("  • Select from the numbered options below", type: :info)
    display_message("  • Enter the number of your choice", type: :info)
    display_message("  • Press Enter to confirm", type: :info)
  when "confirmation"
    display_message("  • Enter 'y' or 'yes' for Yes", type: :info)
    display_message("  • Enter 'n' or 'no' for No", type: :info)
    display_message("  • Press Enter for default", type: :info)
  when "file"
    display_message("  • Enter file path directly", type: :info)
    display_message("  • Use @ to browse and select files", type: :info)
    display_message("  • File must exist and be readable", type: :info)
  when "number"
    display_message("  • Enter a valid number", type: :info)
    display_message("  • Use decimal point for decimals", type: :info)
    display_message("  • Press Enter when done", type: :info)
  when "email"
    display_message("  • Enter a valid email address", type: :info)
    display_message("  • Format: [email protected]", type: :info)
    display_message("  • Press Enter when done", type: :info)
  when "url"
    display_message("  • Enter a valid URL", type: :info)
    display_message("  • Format: https://example.com", type: :info)
    display_message("  • Press Enter when done", type: :info)
  end

  # Additional instructions based on options
  if options && !options.empty?
    display_message("\n📋 Available Options:", type: :info)
    options.each_with_index do |option, index|
      marker = (default_value && option == default_value) ? " (default)" : ""
      display_message("  #{index + 1}. #{option}#{marker}", type: :info)
    end
  end

  # Default value instructions
  if default_value
    display_message("\n⚡ Quick Answer:", type: :info)
    display_message("  • Press Enter to use default: #{default_value}", type: :info)
  end

  # Required field instructions
  if required
    display_message("\n⚠️  Required Field:", type: :info)
    display_message("  • This question must be answered", type: :info)
    display_message("  • Cannot be left blank", type: :info)
  else
    display_message("\n✅ Optional Field:", type: :info)
    display_message("  • This question can be skipped", type: :info)
    display_message("  • Press Enter to leave blank", type: :info)
  end
end

#display_question_metadata(question_type, expected_input, options, default_value, required) ⇒ Object

Display question metadata



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/aidp/harness/user_interface.rb', line 274

def (question_type, expected_input, options, default_value, required)
  display_message("\n📋 Question Details:", type: :info)

  # Question type
  display_message("  Type: #{question_type.capitalize}", type: :info)

  # Expected input
  if expected_input != "text"
    display_message("  Expected input: #{expected_input}", type: :info)
  end

  # Options
  if options && !options.empty?
    display_message("  Options: #{options.length} available", type: :info)
  end

  # Default value
  if default_value
    display_message("  Default: #{default_value}", type: :info)
  end

  # Required status
  status = required ? "Required" : "Optional"
  status_emoji = required ? "🔴" : "🟢"
  display_message("  Status: #{status_emoji} #{status}", type: :info)
end

#display_question_overview(questions) ⇒ Object

Display question overview



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/aidp/harness/user_interface.rb', line 154

def display_question_overview(questions)
  total_questions = questions.length
  required_questions = questions.count { |q| q[:required] != false }
  optional_questions = total_questions - required_questions

  question_types = questions.map { |q| q[:type] || "text" }.uniq

  display_message("📊 Overview:", type: :info)
  display_message("  Total questions: #{total_questions}", type: :info)
  display_message("  Required: #{required_questions}", type: :info)
  display_message("  Optional: #{optional_questions}", type: :info)
  display_message("  Question types: #{question_types.join(", ")}", type: :info)

  # Estimate completion time
  estimated_time = estimate_completion_time(questions)
  display_message("  Estimated time: #{estimated_time}", type: :info)
end

#display_question_presentation_header(questions, context) ⇒ Object

Display question presentation header



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/aidp/harness/user_interface.rb', line 137

def display_question_presentation_header(questions, context)
  display_message("\n🤖 Agent needs your feedback:", type: :highlight)
  display_message("=" * 60, type: :muted)

  # Display question overview
  display_question_overview(questions)

  # Display context summary if available
  if context
    display_context_summary(context)
  end

  display_message("\n📝 Questions to answer:", type: :info)
  display_message("-" * 40, type: :muted)
end

#display_question_progress(current_index, total_questions) ⇒ Object

Display question progress



364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/aidp/harness/user_interface.rb', line 364

def display_question_progress(current_index, total_questions)
  progress_percentage = (current_index.to_f / total_questions * 100).round(1)
  progress_bar = generate_progress_bar(progress_percentage)

  display_message("\n📊 Progress: #{progress_bar} #{progress_percentage}% (#{current_index}/#{total_questions})", type: :info)

  # Show estimated time remaining
  if current_index < total_questions
    remaining_questions = total_questions - current_index
    estimated_remaining = estimate_remaining_time(remaining_questions)
    display_message("⏱️  Estimated time remaining: #{estimated_remaining}", type: :info)
  end
end

#display_question_summary(questions) ⇒ Object

Display question summary



1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
# File 'lib/aidp/harness/user_interface.rb', line 1832

def display_question_summary(questions)
  display_message("\n📋 Question Summary:", type: :info)
  display_message("-" * 30, type: :info)

  questions.each_with_index do |question_data, index|
    question_number = question_data[:number] || (index + 1)
    question_text = question_data[:question]
    question_type = question_data[:type] || "text"
    required = question_data[:required] != false

    status = required ? "Required" : "Optional"
    type_emojis = {
      "text" => "📝",
      "choice" => "🔘",
      "confirmation" => "",
      "file" => "📁",
      "number" => "🔢",
      "email" => "📧",
      "url" => "🔗"
    }
    type_emoji = type_emojis[question_type] || ""

    display_message("  #{question_number}. #{type_emoji} #{question_text} (#{status})", type: :info)
  end
end

#display_question_text(question_text, question_type) ⇒ Object

Display question text with formatting



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/aidp/harness/user_interface.rb', line 257

def display_question_text(question_text, question_type)
  # Get question type emoji
  type_emojis = {
    "text" => "📝",
    "choice" => "🔘",
    "confirmation" => "",
    "file" => "📁",
    "number" => "🔢",
    "email" => "📧",
    "url" => "🔗"
  }
  type_emoji = type_emojis[question_type] || ""

  display_message("#{type_emoji} #{question_text}", type: :info)
end

#display_validation_error(validation_result, _input_type) ⇒ Object

Enhanced error handling and validation display



547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'lib/aidp/harness/user_interface.rb', line 547

def display_validation_error(validation_result, _input_type)
  display_message("\n❌ Validation Error:", type: :error)
  display_message("  #{validation_result[:error_message]}", type: :error)

  if validation_result[:suggestions].any?
    display_message("\n💡 Suggestions:", type: :info)
    validation_result[:suggestions].each do |suggestion|
      display_message("#{suggestion}", type: :info)
    end
  end

  if validation_result[:warnings].any?
    display_message("\n⚠️  Warnings:", type: :warning)
    validation_result[:warnings].each do |warning|
      display_message("#{warning}", type: :warning)
    end
  end

  display_message("\n🔄 Please try again...", type: :info)
end

#display_validation_warnings(validation_result) ⇒ Object

Display validation warnings



569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/aidp/harness/user_interface.rb', line 569

def display_validation_warnings(validation_result)
  if validation_result[:warnings].any?
    display_message("\n⚠️  Warnings:", type: :warning)
    validation_result[:warnings].each do |warning|
      display_message("#{warning}", type: :warning)
    end
    display_message("\nPress Enter to continue or type 'fix' to correct...", type: :info)

    input = @prompt.ask("")
    return input&.strip&.downcase == "fix"
  end
  false
end

#email_response(default_value, required, options = {}) ⇒ Object

Get email response with enhanced validation



795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# File 'lib/aidp/harness/user_interface.rb', line 795

def email_response(default_value, required, options = {})
  prompt = "Email address"
  prompt += " (default: #{default_value})" if default_value
  prompt += required ? ": " : " (optional): "

  loop do
    input = @prompt.ask(prompt)

    if input.nil? || input.strip.empty?
      if default_value
        return default_value
      elsif required
        display_message("❌ Please provide an email address.", type: :error)
        next
      else
        return nil
      end
    end

    # Enhanced validation for email
    validation_result = validate_input_type(input.strip, "email", options)

    unless validation_result[:valid]
      display_validation_error(validation_result, "email")
      next
    end

    # Check for warnings
    if display_validation_warnings(validation_result)
      next
    end

    return input.strip
  end
end

#emergency_stopObject

Emergency stop



2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
# File 'lib/aidp/harness/user_interface.rb', line 2359

def emergency_stop
  display_message("\n🚨 EMERGENCY STOP INITIATED", type: :error)
  display_message("=" * 50, type: :muted)
  display_message("All execution will be halted immediately.", type: :error)
  display_message("This action cannot be undone.", type: :error)
  display_message("=" * 50, type: :muted)

  @control_mutex.synchronize do
    @stop_requested = true
    @pause_requested = false
    @resume_requested = false
  end

  stop_control_interface
  display_message("🛑 Emergency stop completed.", type: :error)
end

#enable_control_interfaceObject

Enable control interface



2237
2238
2239
2240
# File 'lib/aidp/harness/user_interface.rb', line 2237

def enable_control_interface
  @control_interface_enabled = true
  display_message("🎮 Control interface enabled", type: :success)
end

#estimate_completion_time(questions) ⇒ Object

Estimate completion time for questions



196
197
198
199
200
201
202
203
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
# File 'lib/aidp/harness/user_interface.rb', line 196

def estimate_completion_time(questions)
  total_time = 0

  questions.each do |question|
    question_type = question[:type] || "text"

    total_time += case question_type
    when "text"
      30 # 30 seconds for text input
    when "choice"
      15 # 15 seconds for choice selection
    when "confirmation"
      10 # 10 seconds for yes/no
    when "file"
      45 # 45 seconds for file selection
    when "number"
      20 # 20 seconds for number input
    when "email"
      25 # 25 seconds for email input
    when "url"
      30 # 30 seconds for URL input
    else
      30 # Default 30 seconds
    end
  end

  if total_time < 60
    "#{total_time} seconds"
  else
    minutes = (total_time / 60.0).round(1)
    "#{minutes} minutes"
  end
end

#estimate_remaining_time(remaining_questions) ⇒ Object

Estimate remaining time



387
388
389
390
391
392
393
394
395
396
397
# File 'lib/aidp/harness/user_interface.rb', line 387

def estimate_remaining_time(remaining_questions)
  # Assume average 25 seconds per question
  total_seconds = remaining_questions * 25

  if total_seconds < 60
    "#{total_seconds} seconds"
  else
    minutes = (total_seconds / 60.0).round(1)
    "#{minutes} minutes"
  end
end

#file_info(file) ⇒ Object

Get file information for display



1560
1561
1562
1563
1564
1565
1566
1567
# File 'lib/aidp/harness/user_interface.rb', line 1560

def file_info(file)
  {
    display_name: file,
    size: format_file_size(File.size(file)),
    modified: File.mtime(file).strftime("%Y-%m-%d %H:%M"),
    type: file_type(file)
  }
end

#file_response(_expected_input, default_value, required, options = {}) ⇒ Object

Get file response with enhanced validation



705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
# File 'lib/aidp/harness/user_interface.rb', line 705

def file_response(_expected_input, default_value, required, options = {})
  prompt = "File path"
  prompt += " (default: #{default_value})" if default_value
  prompt += required ? ": " : " (optional): "

  loop do
    input = @prompt.ask(prompt)

    if input.nil? || input.strip.empty?
      if default_value
        return default_value
      elsif required
        display_message("❌ Please provide a file path.", type: :error)
        next
      else
        return nil
      end
    end

    # Handle file selection with @ character
    if input.strip.start_with?("@")
      file_path = handle_file_selection(input.strip)
      return file_path if file_path
    else
      # Enhanced validation for file path
      validation_result = validate_input_type(input.strip, "file", options)

      unless validation_result[:valid]
        display_validation_error(validation_result, "file")
        next
      end

      # Check for warnings
      if display_validation_warnings(validation_result)
        next
      end

      return input.strip
    end
  end
end

#file_type(file) ⇒ Object

Get file type for display



1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
# File 'lib/aidp/harness/user_interface.rb', line 1581

def file_type(file)
  ext = File.extname(file)
  case ext
  when ".rb"
    "Ruby"
  when ".js"
    "JavaScript"
  when ".ts"
    "TypeScript"
  when ".py"
    "Python"
  when ".md"
    "Markdown"
  when ".yml", ".yaml"
    "YAML"
  when ".json"
    "JSON"
  when ".xml"
    "XML"
  when ".html", ".htm"
    "HTML"
  when ".css"
    "CSS"
  when ".scss", ".sass"
    "Sass"
  when ".sql"
    "SQL"
  when ".sh"
    "Shell"
  when ".txt"
    "Text"
  else
    ext.empty? ? "File" : ext[1..].upcase
  end
end

#find_files_advanced(search_options) ⇒ Object

Find files with advanced search options



1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
# File 'lib/aidp/harness/user_interface.rb', line 1396

def find_files_advanced(search_options)
  files = []

  # Determine search paths
  search_paths = determine_search_paths(search_options)

  search_paths.each do |path|
    next unless Dir.exist?(path)

    # Use appropriate glob pattern
    glob_pattern = build_glob_pattern(path, search_options)

    Dir.glob(glob_pattern).each do |file|
      next unless File.file?(file)

      # Apply filters
      if matches_filters?(file, search_options)
        files << file
      end
    end
  end

  # Sort and limit results
  files = sort_files(files, search_options)
  files.first(search_options[:max_results])
end

#format_file_size(size) ⇒ Object

Format file size for display



1570
1571
1572
1573
1574
1575
1576
1577
1578
# File 'lib/aidp/harness/user_interface.rb', line 1570

def format_file_size(size)
  if size < 1024
    "#{size} B"
  elsif size < 1024 * 1024
    "#{(size / 1024.0).round(1)} KB"
  else
    "#{(size / (1024.0 * 1024.0)).round(1)} MB"
  end
end

#generate_progress_bar(percentage, width = 20) ⇒ Object

Generate progress bar



379
380
381
382
383
384
# File 'lib/aidp/harness/user_interface.rb', line 379

def generate_progress_bar(percentage, width = 20)
  filled = (percentage / 100.0 * width).round
  empty = width - filled

  "[" + "" * filled + "" * empty + "]"
end

#handle_file_selection(input) ⇒ Object

Handle file selection interface



1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
# File 'lib/aidp/harness/user_interface.rb', line 1308

def handle_file_selection(input)
  # Remove @ character and any following text
  search_term = input[1..].strip

  # Parse search options
  search_options = parse_file_search_options(search_term)

  # Get available files with advanced search
  available_files = find_files_advanced(search_options)

  if available_files.empty?
    display_message("No files found matching '#{search_options[:term]}'. Please try again.", type: :warning)
    display_message("💡 Try: @ (all files), @.rb (Ruby files), @config (files with 'config'), @lib/ (files in lib directory)", type: :info)
    return nil
  end

  # Display file selection menu with advanced features
  display_advanced_file_menu(available_files, search_options)

  # Get user selection with advanced options
  selection = advanced_file_selection(available_files.size, search_options)

  if selection && selection >= 0 && selection < available_files.size
    selected_file = available_files[selection]
    display_message("✅ Selected: #{selected_file}", type: :success)

    # Show file preview if requested
    if search_options[:preview]
      show_file_preview(selected_file)
    end

    selected_file
  elsif selection == -1
    # User wants to refine search
    handle_file_selection("@#{search_term}")
  else
    display_message("❌ Invalid selection. Please try again.", type: :error)
    nil
  end
end

#handle_input_error(error, question_data, retry_count = 0) ⇒ Object

Comprehensive error recovery system



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'lib/aidp/harness/user_interface.rb', line 461

def handle_input_error(error, question_data, retry_count = 0)
  max_retries = 3

  display_message("\n🚨 Input Error:", type: :error)
  display_message("  #{error.message}", type: :error)

  if retry_count < max_retries
    display_message("\n🔄 Retry Options:", type: :info)
    display_message("  1. Try again", type: :info)
    display_message("  2. Skip this question", type: :info)
    display_message("  3. Get help", type: :info)
    display_message("  4. Cancel all questions", type: :info)

    choice = @prompt.select("Choose an option:", {
      "Try again" => "1",
      "Skip this question" => "2",
      "Get help" => "3",
      "Cancel all questions" => "4"
    })

    case choice
    when "1"
      display_message("🔄 Retrying...", type: :info)
      :retry
    when "2"
      display_message("⏭️  Skipping question...", type: :warning)
      :skip
    when "3"
      show_question_help(question_data)
      :retry
    when "4"
      display_message("❌ Cancelling all questions...", type: :error)
      :cancel
    else
      display_message("❌ Invalid choice. Retrying...", type: :error)
      :retry
    end
  else
    display_message("\n❌ Maximum retries exceeded. Skipping question...", type: :error)
    :skip
  end
end

#handle_pause_stateObject

Handle pause state



2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
# File 'lib/aidp/harness/user_interface.rb', line 2113

def handle_pause_state
  display_message("\n⏸️  HARNESS PAUSED", type: :warning)
  display_message("=" * 50, type: :muted)
  display_message("🎮 Control Options:", type: :info)
  display_message("   'r' + Enter: Resume execution", type: :info)
  display_message("   's' + Enter: Stop execution", type: :info)
  display_message("   'h' + Enter: Show help", type: :info)
  display_message("   'q' + Enter: Quit control interface", type: :info)
  display_message("=" * 50, type: :muted)

  loop do
    input = @prompt.ask("Paused>")

    case input&.strip&.downcase
    when "r", "resume"
      request_resume
      break
    when "s", "stop"
      request_stop
      break
    when "h", "help"
      show_control_help
    when "q", "quit"
      stop_control_interface
      break
    else
      display_message("❌ Invalid command. Type 'h' for help.", type: :error)
    end
  end
end

#handle_resume_stateObject

Handle resume state



2154
2155
2156
2157
2158
2159
# File 'lib/aidp/harness/user_interface.rb', line 2154

def handle_resume_state
  display_message("\n▶️  HARNESS RESUMED", type: :success)
  display_message("=" * 50, type: :muted)
  display_message("Execution has been resumed.", type: :info)
  display_message("=" * 50, type: :muted)
end

#handle_stop_stateObject

Handle stop state



2145
2146
2147
2148
2149
2150
2151
# File 'lib/aidp/harness/user_interface.rb', line 2145

def handle_stop_state
  display_message("\n🛑 HARNESS STOPPED", type: :error)
  display_message("=" * 50, type: :muted)
  display_message("Execution has been stopped by user request.", type: :info)
  display_message("You can restart the harness from where it left off.", type: :info)
  display_message("=" * 50, type: :muted)
end

#input_historyObject

Get input history



1787
1788
1789
# File 'lib/aidp/harness/user_interface.rb', line 1787

def input_history
  @input_history.dup
end

#mark_question_type_seen(question_type, seen_types) ⇒ Object

Mark question type as seen



1908
1909
1910
# File 'lib/aidp/harness/user_interface.rb', line 1908

def mark_question_type_seen(question_type, seen_types)
  seen_types << question_type
end

#matches_filters?(file, search_options) ⇒ Boolean

Check if file matches search filters

Returns:

  • (Boolean)


1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
# File 'lib/aidp/harness/user_interface.rb', line 1456

def matches_filters?(file, search_options)
  filename = File.basename(file)
  filepath = file

  # Apply case sensitivity
  if search_options[:case_sensitive]
    filename_to_check = filename
    term_to_check = search_options[:term]
  else
    filename_to_check = filename.downcase
    term_to_check = search_options[:term]&.downcase
  end

  # Check term match
  if search_options[:term] && search_options[:term].empty?
    true
  elsif search_options[:patterns]&.any?
    # Check if any pattern matches
    search_options[:patterns].any? do |pattern|
      pattern_to_check = search_options[:case_sensitive] ? pattern : pattern.downcase
      filename_to_check.include?(pattern_to_check) || filepath.include?(pattern_to_check)
    end
  else
    # Simple term matching
    filename_to_check.include?(term_to_check) || filepath.include?(term_to_check)
  end
end

#number_response(expected_input, default_value, required, options = {}) ⇒ Object

Get number response with enhanced validation



748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/aidp/harness/user_interface.rb', line 748

def number_response(expected_input, default_value, required, options = {})
  prompt = "Number"
  prompt += " (default: #{default_value})" if default_value
  prompt += required ? ": " : " (optional): "

  loop do
    input = @prompt.ask(prompt)

    if input.nil? || input.strip.empty?
      if default_value
        return default_value
      elsif required
        display_message("❌ Please provide a number.", type: :error)
        next
      else
        return nil
      end
    end

    # Enhanced validation for numbers
    validation_result = validate_input_type(input.strip, expected_input, options)

    unless validation_result[:valid]
      display_validation_error(validation_result, expected_input)
      next
    end

    # Check for warnings
    if display_validation_warnings(validation_result)
      next
    end

    # Parse the number
    begin
      if expected_input == "integer"
        return Integer(input.strip)
      else
        return Float(input.strip)
      end
    rescue ArgumentError
      display_message("❌ Please enter a valid #{expected_input}.", type: :error)
      next
    end
  end
end

#parse_file_search_options(search_term) ⇒ Object

Parse file search options from search term



1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
# File 'lib/aidp/harness/user_interface.rb', line 1350

def parse_file_search_options(search_term)
  options = {
    term: search_term,
    extensions: [],
    directories: [],
    patterns: [],
    preview: false,
    case_sensitive: false,
    max_results: 50
  }

  # Parse extension filters (e.g., .rb, .js, .py)
  if search_term.match?(/\.\w+$/)
    options[:extensions] = [search_term]
    options[:term] = ""
  end

  # Parse directory filters (e.g., lib/, spec/, app/)
  if search_term.match?(/^[^\/]+\/$/)
    options[:directories] = [search_term.chomp("/")]
    options[:term] = ""
  end

  # Parse pattern filters (e.g., config, test, spec)
  if search_term.match?(/^[a-zA-Z_][a-zA-Z0-9_]*$/)
    options[:patterns] = [search_term]
  end

  # Parse special options
  if search_term.include?("preview")
    options[:preview] = true
    options[:term] = options[:term].gsub("preview", "").strip
  end

  if search_term.include?("case")
    options[:case_sensitive] = true
    options[:term] = options[:term].gsub("case", "").strip
  end

  # Clean up multiple spaces
  options[:term] = options[:term].gsub(/\s+/, " ").strip

  options
end

#pause_requested?Boolean

Check if pause is requested

Returns:

  • (Boolean)


2041
2042
2043
# File 'lib/aidp/harness/user_interface.rb', line 2041

def pause_requested?
  @control_mutex.synchronize { !!@pause_requested }
end

Helper method to print to stderr with flush



1781
1782
1783
1784
# File 'lib/aidp/harness/user_interface.rb', line 1781

def print_to_stderr(*parts)
  parts.each { |part| $stderr.print part }
  $stderr.flush
end

#question_response(question_data, _question_number) ⇒ Object

Get response for a specific question with enhanced validation



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/aidp/harness/user_interface.rb', line 432

def question_response(question_data, _question_number)
  question_type = question_data[:type] || "text"
  expected_input = question_data[:expected_input] || "text"
  options = question_data[:options]
  default_value = question_data[:default]
  required = question_data[:required] != false
  validation_options = question_data[:validation_options] || {}

  case question_type
  when "text"
    text_response(expected_input, default_value, required, validation_options)
  when "choice"
    choice_response(options, default_value, required)
  when "confirmation"
    confirmation_response(default_value, required)
  when "file"
    file_response(expected_input, default_value, required, validation_options)
  when "number"
    number_response(expected_input, default_value, required, validation_options)
  when "email"
    email_response(default_value, required, validation_options)
  when "url"
    url_response(default_value, required, validation_options)
  else
    text_response(expected_input, default_value, required, validation_options)
  end
end

#quick_feedback(question, options = {}) ⇒ Object

Get quick feedback for simple questions



1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
# File 'lib/aidp/harness/user_interface.rb', line 1946

def quick_feedback(question, options = {})
  question_type = options[:type] || "text"
  default_value = options[:default]
  required = options[:required] != false

  display_message("\n❓ #{question}", type: :info)

  case question_type
  when "text"
    text_response("text", default_value, required)
  when "confirmation"
    confirmation_response(default_value, required)
  when "choice"
    choice_response(options[:options], default_value, required)
  else
    text_response("text", default_value, required)
  end
end

#quick_pauseObject

Quick control commands



2318
2319
2320
2321
# File 'lib/aidp/harness/user_interface.rb', line 2318

def quick_pause
  request_pause
  display_message("⏸️  Quick pause requested. Use 'r' to resume.", type: :warning)
end

#quick_resumeObject



2323
2324
2325
2326
# File 'lib/aidp/harness/user_interface.rb', line 2323

def quick_resume
  request_resume
  display_message("▶️  Quick resume requested.", type: :success)
end

#quick_stopObject



2328
2329
2330
2331
# File 'lib/aidp/harness/user_interface.rb', line 2328

def quick_stop
  request_stop
  display_message("🛑 Quick stop requested.", type: :error)
end

#request_pauseObject

Request pause



2056
2057
2058
2059
2060
2061
2062
# File 'lib/aidp/harness/user_interface.rb', line 2056

def request_pause
  @control_mutex.synchronize do
    @pause_requested = true
    @resume_requested = false
  end
  display_message("\n⏸️  Pause requested...", type: :warning)
end

#request_resumeObject

Request resume



2075
2076
2077
2078
2079
2080
2081
# File 'lib/aidp/harness/user_interface.rb', line 2075

def request_resume
  @control_mutex.synchronize do
    @resume_requested = true
    @pause_requested = false
  end
  display_message("\n▶️  Resume requested...", type: :success)
end

#request_stopObject

Request stop



2065
2066
2067
2068
2069
2070
2071
2072
# File 'lib/aidp/harness/user_interface.rb', line 2065

def request_stop
  @control_mutex.synchronize do
    @stop_requested = true
    @pause_requested = false
    @resume_requested = false
  end
  display_message("\n🛑 Stop requested...", type: :error)
end

#resume_requested?Boolean

Check if resume is requested

Returns:

  • (Boolean)


2051
2052
2053
# File 'lib/aidp/harness/user_interface.rb', line 2051

def resume_requested?
  @control_mutex.synchronize { !!@resume_requested }
end

#setup_control_interfaceObject



59
60
61
62
63
64
65
66
# File 'lib/aidp/harness/user_interface.rb', line 59

def setup_control_interface
  @control_interface_enabled = true
  @pause_requested = false
  @stop_requested = false
  @resume_requested = false
  @control_thread = nil
  @control_mutex = Mutex.new
end

#should_show_help?(question_type, seen_types) ⇒ Boolean

Check if help should be shown

Returns:

  • (Boolean)


1901
1902
1903
1904
1905
# File 'lib/aidp/harness/user_interface.rb', line 1901

def should_show_help?(question_type, seen_types)
  return false unless @show_help_automatically

  !seen_types.include?(question_type)
end

#show_control_helpObject

Show control help



2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
# File 'lib/aidp/harness/user_interface.rb', line 2162

def show_control_help
  display_message("\n📖 Control Interface Help", type: :info)
  display_message("=" * 50, type: :muted)
  display_message("🎮 Available Commands:", type: :info)
  display_message("   'p' or 'pause'    - Pause the harness execution", type: :info)
  display_message("   'r' or 'resume'   - Resume the harness execution", type: :info)
  display_message("   's' or 'stop'     - Stop the harness execution", type: :info)
  display_message("   'h' or 'help'     - Show this help message", type: :info)
  display_message("   'q' or 'quit'     - Quit the control interface", type: :info)
  display_message("", type: :info)
  display_message("📋 Control States:", type: :info)
  display_message("   Running  - Harness is executing normally", type: :info)
  display_message("   Paused   - Harness is paused, waiting for resume", type: :info)
  display_message("   Stopped  - Harness has been stopped by user", type: :info)
  display_message("   Resumed  - Harness has been resumed from pause", type: :info)
  display_message("", type: :info)
  display_message("💡 Tips:", type: :info)
  display_message("   • You can pause/resume/stop at any time during execution", type: :info)
  display_message("   • The harness will save its state when paused/stopped", type: :info)
  display_message("   • You can restart from where you left off", type: :info)
  display_message("   • Use 'h' for help at any time", type: :info)
  display_message("=" * 50, type: :muted)
end

#show_control_menuObject

Interactive control menu



2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
# File 'lib/aidp/harness/user_interface.rb', line 2277

def show_control_menu
  display_message("\n🎮 Harness Control Menu", type: :info)
  display_message("=" * 50, type: :muted)
  display_message("1. Start Control Interface", type: :info)
  display_message("2. Stop Control Interface", type: :info)
  display_message("3. Pause Harness", type: :info)
  display_message("4. Resume Harness", type: :info)
  display_message("5. Stop Harness", type: :info)
  display_message("6. Show Control Status", type: :info)
  display_message("7. Show Help", type: :info)
  display_message("8. Exit Menu", type: :info)
  display_message("=" * 50, type: :muted)

  loop do
    choice = @prompt.ask("Select option (1-8): ")

    case choice&.strip
    when "1"
      start_control_interface
    when "2"
      stop_control_interface
    when "3"
      request_pause
    when "4"
      request_resume
    when "5"
      request_stop
    when "6"
      display_control_status
    when "7"
      show_control_help
    when "8"
      display_message("👋 Exiting control menu...", type: :info)
      break
    else
      display_message("❌ Invalid option. Please select 1-8.", type: :error)
    end
  end
end

#show_file_preview(file_path) ⇒ Object

Show file preview



1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
# File 'lib/aidp/harness/user_interface.rb', line 1684

def show_file_preview(file_path)
  display_message("\n📄 File Preview: #{file_path}", type: :highlight)
  display_message("=" * 60, type: :muted)

  begin
    content = File.read(file_path)
    lines = content.lines

    display_message("📊 File Info:", type: :info)
    display_message("  Size: #{format_file_size(File.size(file_path))}", type: :info)
    display_message("  Lines: #{lines.count}", type: :info)
    display_message("  Modified: #{File.mtime(file_path).strftime("%Y-%m-%d %H:%M:%S")}", type: :info)
    display_message("  Type: #{file_type(file_path)}", type: :info)

    display_message("\n📝 Content Preview (first 20 lines):", type: :info)
    display_message("-" * 40, type: :muted)

    lines.first(20).each_with_index do |line, index|
      display_message("#{(index + 1).to_s.rjust(3)}: #{line.chomp}", type: :info)
    end

    if lines.count > 20
      display_message("... (#{lines.count - 20} more lines)", type: :muted)
    end
  rescue => e
    display_message("❌ Error reading file: #{e.message}", type: :error)
  end

  display_message("\nPress Enter to continue...", type: :info)
  @prompt.keypress("Press any key to continue...")
end

#show_file_selection_helpObject

Show file selection help



1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
# File 'lib/aidp/harness/user_interface.rb', line 1657

def show_file_selection_help
  display_message("\n📖 File Selection Help:", type: :info)
  display_message("=" * 40, type: :muted)

  display_message("\n🔍 Search Examples:", type: :info)
  display_message("  @                    - Show all files", type: :info)
  display_message("  @.rb                 - Show Ruby files only", type: :info)
  display_message("  @config              - Show files with 'config' in name", type: :info)
  display_message("  @lib/                - Show files in lib directory", type: :info)
  display_message("  @spec preview        - Show spec files with preview option", type: :info)
  display_message("  @.js case            - Show JavaScript files (case sensitive)", type: :info)

  display_message("\n⌨️  Selection Commands:", type: :info)
  display_message("  1-50                 - Select file by number", type: :info)
  display_message("  0                    - Cancel selection", type: :info)
  display_message("  -1                   - Refine search", type: :info)
  display_message("  p                    - Preview selected file", type: :info)
  display_message("  h                    - Show this help", type: :info)

  display_message("\n💡 Tips:", type: :info)
  display_message("  • Files are sorted by relevance and type", type: :info)
  display_message("  • Use extension filters for specific file types", type: :info)
  display_message("  • Use directory filters to limit search scope", type: :info)
  display_message("  • Preview option shows file content before selection", type: :info)
end

#show_helpObject

Display interactive help



1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
# File 'lib/aidp/harness/user_interface.rb', line 1797

def show_help
  display_message("\n📖 Interactive Prompt Help:", type: :info)
  display_message("=" * 40, type: :info)

  display_message("\n🔤 Input Types:", type: :info)
  display_message("  • Text: Free-form text input", type: :info)
  display_message("  • Choice: Select from predefined options", type: :info)
  display_message("  • Confirmation: Yes/No questions", type: :info)
  display_message("  • File: File path with @ browsing", type: :info)
  display_message("  • Number: Integer or decimal numbers", type: :info)
  display_message("  • Email: Email address format", type: :info)
  display_message("  • URL: Web URL format", type: :info)

  display_message("\n⌨️  Special Commands:", type: :info)
  display_message("  • @: Browse and select files", type: :info)
  display_message("  • Enter: Use default value (if available)", type: :info)
  display_message("  • Ctrl+C: Cancel operation", type: :info)

  display_message("\n📁 File Selection:", type: :info)
  display_message("  • Type @ to browse files", type: :info)
  display_message("  • Type @search to filter files", type: :info)
  display_message("  • Select by number or type 0 to cancel", type: :info)

  display_message("\n✅ Validation:", type: :info)
  display_message("  • Required fields must be filled", type: :info)
  display_message("  • Input format is validated automatically", type: :info)
  display_message("  • Invalid input shows error and retries", type: :info)

  display_message("\n💡 Tips:", type: :info)
  display_message("  • Use Tab for auto-completion", type: :info)
  display_message("  • Arrow keys for history navigation", type: :info)
  display_message("  • Default values are shown in prompts", type: :info)
end

#show_progress(message) ⇒ Object

Display progress message



1771
1772
1773
# File 'lib/aidp/harness/user_interface.rb', line 1771

def show_progress(message)
  print_to_stderr(@cursor.clear_line, @cursor.column(1), message)
end

#show_question_help(question_data) ⇒ Object

Show help for specific question



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/aidp/harness/user_interface.rb', line 505

def show_question_help(question_data)
  question_type = question_data[:type] || "text"

  display_message("\n📖 Help for #{question_type.capitalize} Question:", type: :info)
  display_message("=" * 50, type: :muted)

  case question_type
  when "text"
    display_message("• Enter any text response", type: :info)
    display_message("• Use @ for file selection if needed", type: :info)
    display_message("• Press Enter when done", type: :info)
  when "choice"
    display_message("• Select from the numbered options", type: :info)
    display_message("• Enter the number of your choice", type: :info)
    display_message("• Or type the option text directly", type: :info)
  when "confirmation"
    display_message("• Enter 'y' or 'yes' for Yes", type: :info)
    display_message("• Enter 'n' or 'no' for No", type: :info)
    display_message("• Press Enter for default", type: :info)
  when "file"
    display_message("• Enter file path directly", type: :info)
    display_message("• Use @ to browse and select files", type: :info)
    display_message("• File must exist and be readable", type: :info)
  when "number"
    display_message("• Enter a valid number", type: :info)
    display_message("• Use decimal point for decimals", type: :info)
    display_message("• Check range requirements", type: :info)
  when "email"
    display_message("• Enter a valid email address", type: :info)
    display_message("• Format: [email protected]", type: :info)
    display_message("• Check for typos", type: :info)
  when "url"
    display_message("• Enter a valid URL", type: :info)
    display_message("• Format: https://example.com", type: :info)
    display_message("• Include protocol (http:// or https://)", type: :info)
  end

  display_message("\nPress Enter to continue...", type: :info)
  @prompt.keypress("Press any key to continue...")
end

#sort_files(files, search_options) ⇒ Object

Sort files by relevance and type



1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
# File 'lib/aidp/harness/user_interface.rb', line 1485

def sort_files(files, search_options)
  files.sort_by do |file|
    filename = File.basename(file)
    ext = File.extname(file)

    # Priority scoring
    score = 0

    # Exact filename match gets highest priority
    if filename.downcase == search_options[:term].downcase
      score += 1000
    end

    # Filename starts with search term
    if filename.downcase.start_with?(search_options[:term].downcase)
      score += 500
    end

    # Filename contains search term
    if filename.downcase.include?(search_options[:term].downcase)
      score += 100
    end

    # File type priority
    case ext
    when ".rb"
      score += 50
    when ".js", ".ts"
      score += 40
    when ".py"
      score += 40
    when ".md"
      score += 30
    when ".yml", ".yaml"
      score += 30
    when ".json"
      score += 20
    end

    # Directory priority
    if file.include?("lib/")
      score += 25
    elsif file.include?("spec/") || file.include?("test/")
      score += 20
    elsif file.include?("config/")
      score += 15
    end

    # Shorter paths get slight priority
    score += (100 - file.length)

    [-score, file] # Negative for descending order
  end
end

#start_control_interface(async_control: true) ⇒ Object

Start the control interface



2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
# File 'lib/aidp/harness/user_interface.rb', line 2000

def start_control_interface(async_control: true)
  return unless @control_interface_enabled

  @control_mutex.synchronize do
    return if @control_future&.pending?

    if async_control
      begin
        require "concurrent"
        @control_future = Concurrent::Future.execute { control_interface_loop }
      rescue LoadError
        # Fallback: run a single synchronous loop iteration if concurrent not available
        control_interface_loop_iteration
      end
    else
      control_interface_loop_iteration
    end
  end

  display_message("\n🎮 Control Interface Started", type: :success)
  display_message("   Press 'p' + Enter to pause", type: :info)
  display_message("   Press 'r' + Enter to resume", type: :info)
  display_message("   Press 's' + Enter to stop", type: :info)
  display_message("   Press 'h' + Enter for help", type: :info)
  display_message("   Press 'q' + Enter to quit control interface", type: :info)
  display_message("=" * 50, type: :muted)
end

#stop_control_interfaceObject

Stop the control interface



2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
# File 'lib/aidp/harness/user_interface.rb', line 2029

def stop_control_interface
  @control_mutex.synchronize do
    if @control_future
      @control_future.cancel
      @control_future = nil
    end
  end

  display_message("\n🛑 Control Interface Stopped", type: :info)
end

#stop_requested?Boolean

Check if stop is requested

Returns:

  • (Boolean)


2046
2047
2048
# File 'lib/aidp/harness/user_interface.rb', line 2046

def stop_requested?
  @control_mutex.synchronize { !!@stop_requested }
end

#text_response(expected_input, default_value, required, options = {}) ⇒ Object

Get text response with enhanced validation



584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'lib/aidp/harness/user_interface.rb', line 584

def text_response(expected_input, default_value, required, options = {})
  prompt = "Your response"
  prompt += " (default: #{default_value})" if default_value
  prompt_text = prompt + (required ? "" : " (optional)")

  loop do
    input = input_with_prompt(prompt_text, required: required, default: default_value)

    # get_input_with_prompt already handles required validation and returns non-empty input
    # Only validate the type/format if we got input
    if input.nil?
      # This should only happen for non-required fields
      return nil
    end

    # Enhanced validation
    validation_result = validate_input_type(input.strip, expected_input, options)

    unless validation_result[:valid]
      display_validation_error(validation_result, expected_input)
      next
    end

    # Check for warnings
    if display_validation_warnings(validation_result)
      next
    end

    return input.strip
  end
end

#url_response(default_value, required, options = {}) ⇒ Object

Get URL response with enhanced validation



832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
# File 'lib/aidp/harness/user_interface.rb', line 832

def url_response(default_value, required, options = {})
  prompt = "URL"
  prompt += " (default: #{default_value})" if default_value
  prompt += required ? ": " : " (optional): "

  loop do
    input = @prompt.ask(prompt)

    if input.nil? || input.strip.empty?
      if default_value
        return default_value
      elsif required
        display_message("❌ Please provide a URL.", type: :error)
        next
      else
        return nil
      end
    end

    # Enhanced validation for URL
    validation_result = validate_input_type(input.strip, "url", options)

    unless validation_result[:valid]
      display_validation_error(validation_result, "url")
      next
    end

    # Check for warnings
    if display_validation_warnings(validation_result)
      next
    end

    return input.strip
  end
end

#user_input(prompt) ⇒ Object

Get user input with support for file selection



1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
# File 'lib/aidp/harness/user_interface.rb', line 1285

def user_input(prompt)
  loop do
    input = @prompt.ask(prompt)

    # Handle empty input
    if input.nil? || input.strip.empty?
      display_message("Please provide a response.", type: :error)
      next
    end

    # Handle file selection with @ character
    if input.strip.start_with?("@")
      file_path = handle_file_selection(input.strip)
      return file_path if file_path
    else
      # Add to history and return
      @input_history << input.strip
      return input.strip
    end
  end
end

#user_preferencesObject

Get user preferences for feedback collection



1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
# File 'lib/aidp/harness/user_interface.rb', line 1859

def user_preferences
  display_message("\n⚙️  User Preferences:", type: :info)
  display_message("-" * 25, type: :muted)

  preferences = {}

  # Auto-confirm defaults
  preferences[:auto_confirm_defaults] = confirmation(
    "Auto-confirm default values without prompting?",
    default: false
  )

  # Show help automatically
  preferences[:show_help_automatically] = confirmation(
    "Show help automatically for new question types?",
    default: false
  )

  # Verbose mode
  preferences[:verbose_mode] = confirmation(
    "Enable verbose mode with detailed information?",
    default: true
  )

  # File browsing enabled
  preferences[:file_browsing_enabled] = confirmation(
    "Enable file browsing with @ character?",
    default: true
  )

  preferences
end

#validate_boolean(input, options = {}) ⇒ Object

Validate boolean input



1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
# File 'lib/aidp/harness/user_interface.rb', line 1095

def validate_boolean(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  if input.nil? || input.strip.empty?
    if options[:required]
      result[:error_message] = "Please enter a yes/no response"
    else
      result[:valid] = true
    end
    return result
  end

  response = input.strip.downcase
  valid_responses = %w[y yes n no true false 1 0]

  if !valid_responses.include?(response)
    result[:error_message] = "Invalid response"
    result[:suggestions] = [
      "Enter 'y' or 'yes' for Yes",
      "Enter 'n' or 'no' for No",
      "Enter 'true' or 'false'",
      "Enter '1' for Yes or '0' for No"
    ]
    return result
  end

  result[:valid] = true
  result
end

#validate_choice(input, options = {}) ⇒ Object

Validate choice input



1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
# File 'lib/aidp/harness/user_interface.rb', line 1232

def validate_choice(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  if input.nil? || input.strip.empty?
    result[:error_message] = "Please make a selection"
    return result
  end

  choice = input.strip

  # Check if it's a number selection
  if choice.match?(/\A\d+\z/)
    choice_num = choice.to_i
    if options[:choices] && (choice_num < 1 || choice_num > options[:choices].length)
      result[:error_message] = "Invalid selection number"
      result[:suggestions] = [
        "Enter a number between 1 and #{options[:choices].length}",
        "Available options: #{options[:choices].join(", ")}"
      ]
      return result
    end
  elsif options[:choices] && !options[:choices].include?(choice)
    # Check if it's a direct choice
    result[:error_message] = "Invalid choice"
    result[:suggestions] = [
      "Available options: #{options[:choices].join(", ")}",
      "Or enter the number of your choice"
    ]
    return result
  end

  result[:valid] = true
  result
end

#validate_email(input, options = {}) ⇒ Object

Validate email input



893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
# File 'lib/aidp/harness/user_interface.rb', line 893

def validate_email(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  # Basic email regex
  email_regex = /\A[\w+\-.]+@[a-z\d-]+(\.[a-z\d-]+)*\.[a-z]+\z/i

  if input.nil? || input.strip.empty?
    if options[:required]
      result[:error_message] = "Email address cannot be empty"
    else
      result[:valid] = true
    end
    return result
  end

  if !email_regex.match?(input.strip)
    result[:error_message] = "Invalid email format"
    result[:suggestions] = [
      "Use format: [email protected]",
      "Check for typos in domain name",
      "Ensure @ symbol is present"
    ]
    return result
  end

  # Additional validations
  email = input.strip.downcase
  local_part, domain = email.split("@")

  # Check local part length
  if local_part.length > 64
    result[:warnings] << "Local part is very long (#{local_part.length} characters)"
  end

  # Check domain length
  if domain.length > 253
    result[:warnings] << "Domain is very long (#{domain.length} characters)"
  end

  # Check for common typos
  common_domains = %w[gmail.com yahoo.com hotmail.com outlook.com]
  if common_domains.any? { |d| domain.include?(d) && domain != d }
    result[:suggestions] << "Did you mean #{domain.gsub(/[^a-z.]/, "")}?"
  end

  result[:valid] = true
  result
end

#validate_file_path(input, options = {}) ⇒ Object

Validate file path input



1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
# File 'lib/aidp/harness/user_interface.rb', line 1126

def validate_file_path(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  if input.nil? || input.strip.empty?
    result[:error_message] = "File path cannot be empty"
    return result
  end

  file_path = input.strip

  # Check if file exists
  if !File.exist?(file_path)
    result[:error_message] = "File does not exist: #{file_path}"
    result[:suggestions] = [
      "Check the file path for typos",
      "Use @ to browse and select files",
      "Ensure the file exists in the specified location"
    ]
    return result
  end

  # Check if it's actually a file (not a directory)
  if !File.file?(file_path)
    result[:error_message] = "Path is not a file: #{file_path}"
    result[:suggestions] = [
      "Select a file, not a directory",
      "Use @ to browse files"
    ]
    return result
  end

  # Check file permissions
  if !File.readable?(file_path)
    result[:error_message] = "File is not readable: #{file_path}"
    result[:suggestions] = [
      "Check file permissions",
      "Ensure you have read access to the file"
    ]
    return result
  end

  # File size warning
  file_size = File.size(file_path)
  if file_size > 10 * 1024 * 1024 # 10MB
    result[:warnings] << "Large file size (#{format_file_size(file_size)})"
  end

  # File extension validation
  if options[:allowed_extensions]
    ext = File.extname(file_path).downcase
    if !options[:allowed_extensions].include?(ext)
      result[:warnings] << "Unexpected file extension: #{ext}"
      result[:suggestions] << "Expected extensions: #{options[:allowed_extensions].join(", ")}"
    end
  end

  result[:valid] = true
  result
end

#validate_float(input, options = {}) ⇒ Object

Validate float input



1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
# File 'lib/aidp/harness/user_interface.rb', line 1048

def validate_float(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  if input.nil? || input.strip.empty?
    result[:error_message] = "Number cannot be empty"
    return result
  end

  number_str = input.strip

  # Check for valid float format
  if !number_str.match?(/\A-?\d+(?:\.\d+)?\z/)
    result[:error_message] = "Invalid number format"
    result[:suggestions] = [
      "Enter a number (e.g., 25, 3.14, -10.5)",
      "Use decimal point for decimals",
      "Remove any letters or special characters"
    ]
    return result
  end

  number = number_str.to_f

  # Range validation
  if options[:min] && number < options[:min]
    result[:error_message] = "Number must be at least #{options[:min]}"
    return result
  end

  if options[:max] && number > options[:max]
    result[:error_message] = "Number must be at most #{options[:max]}"
    return result
  end

  # Precision validation
  if options[:precision] && number_str.include?(".")
    decimal_places = number_str.split(".")[1]&.length || 0
    if decimal_places > options[:precision]
      result[:warnings] << "Number has more decimal places than expected (#{decimal_places} > #{options[:precision]})"
    end
  end

  result[:valid] = true
  result
end

#validate_generic(input, options = {}) ⇒ Object

Validate generic input



1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
# File 'lib/aidp/harness/user_interface.rb', line 1268

def validate_generic(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  if input.nil? || input.strip.empty?
    if options[:required]
      result[:error_message] = "Input is required"
    else
      result[:valid] = true
    end
    return result
  end

  result[:valid] = true
  result
end

#validate_input_type(input, expected_type, options = {}) ⇒ Object

Comprehensive input validation system



869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
# File 'lib/aidp/harness/user_interface.rb', line 869

def validate_input_type(input, expected_type, options = {})
  case expected_type
  when "email"
    validate_email(input, options)
  when "url"
    validate_url(input, options)
  when "number", "integer"
    validate_number(input, options)
  when "float", "decimal"
    validate_float(input, options)
  when "boolean"
    validate_boolean(input, options)
  when "file", "path"
    validate_file_path(input, options)
  when "text"
    validate_text(input, options)
  when "choice"
    validate_choice(input, options)
  else
    validate_generic(input, options)
  end
end

#validate_number(input, options = {}) ⇒ Object

Validate number input



1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
# File 'lib/aidp/harness/user_interface.rb', line 1004

def validate_number(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  if input.nil? || input.strip.empty?
    result[:error_message] = "Number cannot be empty"
    return result
  end

  number_str = input.strip

  # Check for valid integer format
  if !number_str.match?(/\A-?\d+\z/)
    result[:error_message] = "Invalid number format"
    result[:suggestions] = [
      "Enter a whole number (e.g., 25, -10, 0)",
      "Remove any decimal points or letters",
      "Check for typos"
    ]
    return result
  end

  number = number_str.to_i

  # Range validation
  if options[:min] && number < options[:min]
    result[:error_message] = "Number must be at least #{options[:min]}"
    return result
  end

  if options[:max] && number > options[:max]
    result[:error_message] = "Number must be at most #{options[:max]}"
    return result
  end

  # Warning for very large numbers
  if number.abs > 1_000_000
    result[:warnings] << "Very large number (#{number})"
  end

  result[:valid] = true
  result
end

#validate_text(input, options = {}) ⇒ Object

Validate text input



1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
# File 'lib/aidp/harness/user_interface.rb', line 1187

def validate_text(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  if input.nil? || input.strip.empty?
    if options[:required]
      result[:error_message] = "Text input is required"
    else
      result[:valid] = true
    end
    return result
  end

  text = input.strip

  # Length validation
  if options[:min_length] && text.length < options[:min_length]
    result[:error_message] = "Text must be at least #{options[:min_length]} characters"
    return result
  end

  if options[:max_length] && text.length > options[:max_length]
    result[:error_message] = "Text must be at most #{options[:max_length]} characters"
    return result
  end

  # Pattern validation
  if options[:pattern] && !text.match?(options[:pattern])
    result[:error_message] = "Text does not match required pattern"
    result[:suggestions] = [
      "Check the format requirements",
      "Ensure all required characters are present"
    ]
    return result
  end

  # Content validation
  if options[:forbidden_words]&.any? { |word| text.downcase.include?(word.downcase) }
    result[:warnings] << "Text contains potentially inappropriate content"
  end

  result[:valid] = true
  result
end

#validate_url(input, options = {}) ⇒ Object

Validate URL input



943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
# File 'lib/aidp/harness/user_interface.rb', line 943

def validate_url(input, options = {})
  result = {valid: false, error_message: nil, suggestions: [], warnings: []}

  if input.nil? || input.strip.empty?
    if options[:required]
      result[:error_message] = "URL cannot be empty"
    else
      result[:valid] = true
    end
    return result
  end

  url = input.strip

  # Basic URL regex
  url_regex = /\Ahttps?:\/\/.+/i

  if !url_regex.match?(url)
    result[:error_message] = "Invalid URL format"
    result[:suggestions] = [
      "Use format: https://example.com",
      "Include http:// or https:// protocol",
      "Check for typos in domain name"
    ]
    return result
  end

  # Additional validations
  begin
    uri = URI.parse(url)

    # Check for valid hostname
    if uri.host.nil? || uri.host.empty?
      result[:error_message] = "Invalid hostname in URL"
      return result
    end

    # Check for common typos
    if uri.host.include?("www.") && !uri.host.start_with?("www.")
      result[:suggestions] << "Consider using www.#{uri.host}"
    end

    # Check for HTTP vs HTTPS
    if uri.scheme == "http" && !uri.host.include?("localhost")
      result[:warnings] << "Consider using HTTPS for security"
    end
  rescue URI::InvalidURIError
    result[:error_message] = "Invalid URL format"
    result[:suggestions] = [
      "Check for special characters",
      "Ensure proper URL encoding",
      "Verify domain name spelling"
    ]
    return result
  end

  result[:valid] = true
  result
end

#wait_for_control_inputObject

Wait for user control input



2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
# File 'lib/aidp/harness/user_interface.rb', line 2093

def wait_for_control_input
  return unless @control_interface_enabled

  loop do
    if pause_requested?
      handle_pause_state
    elsif stop_requested?
      handle_stop_state
      break
    elsif resume_requested?
      handle_resume_state
      break
    else
      # Periodic check for user input/state changes
      sleep(0.1)
    end
  end
end