Class: N2B::IRB

Inherits:
Object
  • Object
show all
Defined in:
lib/n2b/irb.rb

Constant Summary collapse

MAX_SOURCE_FILES =
4
DEFAULT_CONTEXT_LINES =
20

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.n2r(input_string = '', files: [], exception: nil, log: false) ⇒ Object



6
7
8
# File 'lib/n2b/irb.rb', line 6

def self.n2r(input_string='', files: [], exception: nil, log: false)
  new.n2r(input_string, files: files, exception: exception, log: log)
end

.n2rrbit(url:, cookie:, source_dir: nil, context_lines: DEFAULT_CONTEXT_LINES, log: false) ⇒ Object



10
11
12
# File 'lib/n2b/irb.rb', line 10

def self.n2rrbit(url:, cookie:, source_dir: nil, context_lines: DEFAULT_CONTEXT_LINES, log: false)
  new.n2rrbit(url: url, cookie: cookie, source_dir: source_dir, context_lines: context_lines, log: log)
end

.n2rscrum(input_string = '', files: [], exception: nil, url: nil, cookie: nil, source_dir: nil, context_lines: DEFAULT_CONTEXT_LINES, log: false) ⇒ Object



14
15
16
# File 'lib/n2b/irb.rb', line 14

def self.n2rscrum(input_string='', files: [], exception: nil, url: nil, cookie: nil, source_dir: nil, context_lines: DEFAULT_CONTEXT_LINES, log: false)
  new.n2rscrum(input_string: input_string, files: files, exception: exception, url: url, cookie: cookie, source_dir: source_dir, context_lines: context_lines, log: log)
end

Instance Method Details

#n2r(input_string = '', files: [], exception: nil, log: false) ⇒ Object



18
19
20
21
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
# File 'lib/n2b/irb.rb', line 18

def n2r(input_string='', files: [], exception: nil, log: false)
  config = N2B::Base.new.get_config
  llm = case config['llm']
        when 'openai'
          N2M::Llm::OpenAi.new(config)
        when 'gemini'
          N2M::Llm::Gemini.new(config)
        else
          N2M::Llm::Claude.new(config)
        end
  # detect if inside rails console
  console = case 
  when defined?(Rails) && Rails.respond_to?(:application)
    "You are in a Rails console"
  when defined?(IRB)
    "You are in an IRB console"
  else
    "You are in a standard Ruby console"
  end
  get_defined_classes = ObjectSpace.each_object(Class).to_a
  get_gemfile = File.read('Gemfile') if File.exist?('Gemfile') 
  # scan the input for any files that the user has provided
  # look for strings that end with .rb and get the path to the file
  source_files = []
  input_string.scan(/[\w\/.-]+\.rb(?=\s|:|$)/).each do |file|
    full_path = File.expand_path(file) # Resolve the full path
    source_files << full_path if File.exist?(full_path)
  end
  if exception
    source_files += exception.backtrace.map do |line|
      line.split(':').first
    end
    input_string << ' ' << exception.message << "\m" << exception.backtrace.join(' ')
  end
  source_files = source_files.sort_by do |file|
    # Check if the file path starts with the current directory path
    if file.start_with?(Dir.pwd)
      0 # Prioritize files in or below the current directory
    else
      1 # Keep other files in their original order
    end
  end
 
  
  file_content = (files+source_files[0..MAX_SOURCE_FILES-1]).inject({}) do |h,file|
    h[file] = File.read(file) if File.exist?(file)
    h
  end
  content = <<~HEREDOC
    you are a professional ruby programmer  
    #{ console}
    The following classes are defined in this session:
    #{ get_defined_classes}
    #{ get_gemfile }
    #{ @n2r_answers ? "user have made #{@n2r_answers} before" : "" }
    your task is to give the user guidance on how perform a task he is asking for
    if he pasts an error or backtrace, you can provide a solution to the problem.
    if you need files you can ask the user to provide them request.
    he can send them with n2r "his question" files: ['file1.rb', 'file2.rb']
    if he sends files and you mention them in the response, provide the file name of the snippets you are referring to.
    answer in a valid json object with the key 'code' with only the ruby code to be executed and a key 'explanation' with a markdown string with the explanation and the code.
    { "code": "puts 'Hello, World!'", "explanation": "### Explanation \n This command ´´´puts 'Hello, world!'´´´  prints 'Hello, World!' to the terminal.", files: ['file1.rb', 'file2.rb']}
     #{input_string}
    #{ "the user provided the following files: #{ file_content.collect{|k,v| "#{k}:#{v}" }.join("\n") }" if file_content }
    }}
  HEREDOC
  if log
    log_file_path = File.expand_path('~/.n2b/n2r.log')
    File.open(log_file_path, 'a') do |file|
      file.puts(content)
    end
  end
  @n2r_answers ||= []
  @n2r_answer = llm.make_request(content)
  @n2r_answers << { input: input_string, output: @n2r_answer }
  @n2r_answer['code'].split("\n").each do |line|
    puts line
  end if @n2r_answer['code']
  @n2r_answer['explanation'].split("\n").each do |line|
    puts line
  end
  nil
end

#n2rrbit(url:, cookie:, source_dir: nil, context_lines: DEFAULT_CONTEXT_LINES, log: false) ⇒ Object



102
103
104
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
142
143
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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
229
230
231
232
233
234
235
236
# File 'lib/n2b/irb.rb', line 102

def n2rrbit(url:, cookie:, source_dir: nil, context_lines: DEFAULT_CONTEXT_LINES, log: false)
  require 'net/http'
  require 'uri'
  require 'nokogiri'
  
  # Download the Errbit page
  errbit_html = fetch_errbit(url, cookie)
  
  if errbit_html.nil?
    puts "Failed to download Errbit error from #{url}"
    return nil
  end
  
  # Parse the error information
  error_info = parse_errbit(errbit_html)
  
  if error_info.nil?
    puts "Failed to parse Errbit error information"
    return nil
  end
  
  # Find related files in the current project using source_dir if provided
  related_files = find_related_files(error_info[:backtrace], source_dir: source_dir, context_lines: context_lines)
  
  # Analyze the error
  analysis = analyze_error(error_info, related_files)
  
  # Log if requested
  if log
    log_file_path = File.expand_path('~/.n2b/n2rrbit.log')
    File.open(log_file_path, 'a') do |file|
      file.puts("===== N2RRBIT REQUEST LOG =====")
      file.puts("URL: #{url}")
      file.puts("Error: #{error_info[:error_class]} - #{error_info[:error_message]}")
      file.puts("Backtrace: #{error_info[:backtrace].join("\n")}")
      file.puts("Source directory: #{source_dir || Dir.pwd}")
      file.puts("\nFound Related Files:")
      
      # Log detailed information about each file that was found
      related_files.each do |file_path, content|
        file.puts("\n--- File: #{file_path}")
        if content.is_a?(Hash) && content[:full_path]
          file.puts("Full path: #{content[:full_path]}")
          file.puts("Error occurred at line: #{content[:line_number]}")
          file.puts("Context lines: #{content[:start_line]}-#{content[:end_line]}")
          file.puts("\nContext code:")
          file.puts("```ruby")
          file.puts(content[:context])
          file.puts("```")
        else
          file.puts("Full content (no specific line context)")
          file.puts("```ruby")
          file.puts(content)
          file.puts("```")
        end
      end
      
      # Log the actual prompt sent to the LLM
      file_content_section = related_files.map do |file_path, content|
        if content.is_a?(Hash) && content[:context]
          "#{file_path} (around line #{content[:line_number]}, showing lines #{content[:start_line]}-#{content[:end_line]}):\n```ruby\n#{content[:context]}\n```"
        else
          "#{file_path}:\n```ruby\n#{content.is_a?(Hash) ? content[:full_content] : content}\n```"
        end
      end.join("\n\n")
      
      llm_prompt = <<~HEREDOC
        You are an expert Ruby programmer analyzing application errors.
        
        Error Type: #{error_info[:error_class]}
        Error Message: #{error_info[:error_message]}
        Application: #{error_info[:app_name]}
        Environment: #{error_info[:environment]}
        
        Backtrace:
        #{error_info[:backtrace].join("\n")}
        
        Related Files with Context:
        #{file_content_section}
        
        Please analyze this error and provide:
        1. A clear explanation of what caused the error
        2. Specific code that might be causing the issue
        3. Suggested fixes for the problem
        4. If the error seems related to specific parameters, explain which parameter values might be triggering it
        
        Your analysis should be detailed but concise.
      HEREDOC
      
      file.puts("\n=== PROMPT SENT TO LLM ===")
      file.puts(llm_prompt)
      file.puts("\n=== LLM RESPONSE ===")
      file.puts(analysis)
      file.puts("\n===== END OF LOG =====\n\n")
    end
  end
  
  # Display the error analysis
  puts "Error Type: #{error_info[:error_class]}"
  puts "Message: #{error_info[:error_message]}"
  
  if error_info[:parameters] && !error_info[:parameters].empty?
    puts "\nRequest Parameters:"
    error_info[:parameters].each do |key, value|
      # Truncate long values for display
      display_value = value.to_s.length > 100 ? "#{value.to_s[0..100]}..." : value
      puts "  #{key} => #{display_value}"
    end
  end
  
  if error_info[:session] && !error_info[:session].empty?
    puts "\nSession Data:"
    puts "  (Available but not displayed - see log for details)"
  end
  
  puts "\nBacktrace Highlights:"
  error_info[:backtrace].first(5).each do |line|
    puts "  #{line}"
  end
  
  puts "\nSource Directory: #{source_dir || Dir.pwd}"
  puts "\nRelated Files:"
  related_files.each do |file, content|
    if content.is_a?(Hash) && content[:context]
      puts "  #{file} (with context around line #{content[:line_number]})"
    else
      puts "  #{file}"
    end
  end
  
  puts "\nAnalysis:"
  puts analysis
  
  nil
end

#n2rscrum(input_string: '', files: [], exception: nil, url: nil, cookie: nil, source_dir: nil, context_lines: DEFAULT_CONTEXT_LINES, log: false) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
300
301
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
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
430
431
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
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/n2b/irb.rb', line 238

def n2rscrum(input_string: '', files: [], exception: nil, url: nil, cookie: nil, source_dir: nil, context_lines: DEFAULT_CONTEXT_LINES, log: false)
  # Determine which mode we're running in
  if url && cookie
    # Errbit URL mode
    require 'net/http'
    require 'uri'
    require 'nokogiri'
    
    # Download the Errbit page
    errbit_html = fetch_errbit(url, cookie)
    
    if errbit_html.nil?
      puts "Failed to download Errbit error from #{url}"
      return nil
    end
    
    # Parse the error information
    error_info = parse_errbit(errbit_html)
    
    if error_info.nil?
      puts "Failed to parse Errbit error information"
      return nil
    end
    
    # Find related files with context for better analysis
    related_files = find_related_files(error_info[:backtrace], source_dir: source_dir, context_lines: context_lines)
    
    # Generate a Scrum ticket from error info, passing the URL
    ticket = generate_error_ticket(error_info, related_files, url)
  else
    # If we have an exception, convert it to error_info format and use generate_error_ticket
    if exception
      files += exception.backtrace.map do |line|
        line.split(':').first
      end
      
      # Create error_info hash from exception with better Rails detection
      app_name = if defined?(Rails) && Rails.respond_to?(:application) && 
                    Rails.application.respond_to?(:class) &&
                    Rails.application.class.respond_to?(:module_parent_name)
                      Rails.application.class.module_parent_name 
                    else 
                      'Ruby Application'
                    end
      
      environment = if defined?(Rails) && Rails.respond_to?(:env)
                      Rails.env
                    else
                      'development'
                    end
      
      error_info = {
        error_class: exception.class.name,
        error_message: exception.message,
        backtrace: exception.backtrace,
        app_name: app_name,
        environment: environment
      }
      
      # Find related files with context
      related_files = find_related_files(error_info[:backtrace], source_dir: source_dir, context_lines: context_lines)
      
      # Use the same ticket generator for consistency
      ticket = generate_error_ticket(error_info, related_files)
    else
      # Standard mode (input string/files)
      config = N2B::Base.new.get_config
      llm = config['llm'] == 'openai' ? N2M::Llm::OpenAi.new(config) : N2M::Llm::Claude.new(config)
      
      # detect if inside rails console
      console = case 
      when defined?(Rails) && Rails.respond_to?(:application)
        "You are in a Rails console"
      when defined?(IRB)
        "You are in an IRB console"
      else
        "You are in a standard Ruby console"
      end
      
      # Read file contents
      file_content = files.inject({}) do |h, file|
        h[file] = File.read(file) if File.exist?(file)
        h
      end
      
      # Generate ticket content using LLM
      content = <<~HEREDOC
        you are a professional ruby programmer and scrum master
        #{console}
        your task is to create a scrum ticket for the following issue/question:
        answer in a valid json object with the key 'code' with only the ruby code to be executed and a key 'explanation' with a markdown string containing a well-formatted scrum ticket with:
        
        1. A clear and concise title
        2. Description of the issue with technical details
        3. Acceptance criteria
        4. Estimate of complexity (story points)
        5. Priority level suggestion
        
        #{input_string}
        #{"the user provided the following files: #{file_content.collect{|k,v| "#{k}:#{v}" }.join("\n") }" if file_content.any?}
      HEREDOC
      
      response = safe_llm_request(llm, content)
      ticket = response['explanation'] || response['code'] || "Failed to generate Scrum ticket."
    end
  end
  
  # Log if requested
  if log
    log_file_path = File.expand_path('~/.n2b/n2rscrum.log')
    File.open(log_file_path, 'a') do |file|
      file.puts("===== N2RSCRUM REQUEST LOG =====")
      file.puts("Timestamp: #{Time.now}")
      
      if url
        file.puts("Mode: Errbit URL")
        file.puts("URL: #{url}")
      elsif exception
        file.puts("Mode: Exception")
        file.puts("Exception: #{exception.class.name} - #{exception.message}")
      else
        file.puts("Mode: Input String")
        file.puts("Input: #{input_string}")
      end
      
      file.puts("Files: #{files.join(', ')}") if files.any?
      file.puts("Source directory: #{source_dir || Dir.pwd}")
      
      # If we have related files (from Errbit or exception mode)
      if defined?(related_files) && related_files.any?
        file.puts("\nFound Related Files:")
        
        related_files.each do |file_path, content|
          file.puts("\n--- File: #{file_path}")
          if content.is_a?(Hash) && content[:full_path]
            file.puts("Full path: #{content[:full_path]}")
            file.puts("Error occurred at line: #{content[:line_number]}")
            file.puts("Context lines: #{content[:start_line]}-#{content[:end_line]}")
            file.puts("\nContext code:")
            file.puts("```ruby")
            file.puts(content[:context])
            file.puts("```")
          else
            file.puts("Full content (no specific line context)")
            file.puts("```ruby")
            file.puts(content)
            file.puts("```")
          end
        end
        
        # Log the actual prompt sent to the LLM
        file_content_section = related_files.map do |file_path, content|
          if content.is_a?(Hash) && content[:context]
            "#{file_path} (around line #{content[:line_number]}, showing lines #{content[:start_line]}-#{content[:end_line]}):\n```ruby\n#{content[:context]}\n```"
          else
            "#{file_path}:\n```ruby\n#{content.is_a?(Hash) ? content[:full_content] : content}\n```"
          end
        end.join("\n\n")
        
        if defined?(error_info) && error_info
          llm_prompt = <<~HEREDOC
            You are a software developer creating a Scrum task for a bug fix.
            
            Error details:
            Type: #{error_info[:error_class]}
            Message: #{error_info[:error_message]}
            Application: #{error_info[:app_name] || 'Local Application'}
            Environment: #{error_info[:environment] || 'Development'}
            
            Backtrace highlights:
            #{error_info[:backtrace]&.first(5)&.join("\n") || 'No backtrace available'}
            
            Related Files with Context:
            #{file_content_section}
            
            Please generate a well-formatted Scrum ticket that includes:
            1. A clear and concise title
            2. Description of the issue with technical details
            3. Details about the parameter values that were present when the error occurred
            4. Likely root causes and assumptions about what's causing the problem (be specific)
            5. Detailed suggested fixes with code examples where possible
            6. Acceptance criteria
            7. Estimate of complexity (story points)
            8. Priority level suggestion
            
            IMPORTANT: Your response must be a valid JSON object with ONLY two keys:
            - 'explanation': containing the formatted Scrum ticket as a markdown string
            - 'code': set to null or omitted
            
            For example: {"explanation": "# Ticket Title\\n## Description\\n...", "code": null}
            
            Ensure all code examples are properly formatted with markdown code blocks using triple backticks.
          HEREDOC
          
          file.puts("\n=== PROMPT SENT TO LLM ===")
          file.puts(llm_prompt)
        elsif !input_string.empty?
          # Log the prompt for input string mode
          file.puts("\n=== PROMPT SENT TO LLM ===")
          file.puts("Input string mode prompt with input: #{input_string}")
          if file_content.any?
            file.puts("With files content included")
          end
        end
      end
      
      file.puts("\n=== LLM RESPONSE (RAW) ===")
      file.puts(ticket.inspect)
      file.puts("\n=== FORMATTED TICKET ===")
      file.puts(ticket)
      file.puts("\n===== END OF LOG =====\n\n")
    end
  end
  
  # Safely handle the ticket
  begin
    # Display the ticket
    puts "Generated Scrum Ticket:"
    puts ticket

    # Add reference section if URL is provided
    if url
      puts "\n## Reference"
      puts "Errbit URL: #{url}"
    end
  rescue => e
    puts "Error displaying ticket: #{e.message}"
    puts "Raw ticket data: #{ticket.inspect}"
  end
  
  nil
end