Class: Ragdoll::CLI::Main

Inherits:
Thor
  • Object
show all
Defined in:
lib/ragdoll/cli.rb

Instance Method Summary collapse

Constructor Details

#initialize(args = [], local_options = {}, config = {}) ⇒ Main

Returns a new instance of Main.



23
24
25
26
# File 'lib/ragdoll/cli.rb', line 23

def initialize(args = [], local_options = {}, config = {})
  super
  load_configuration
end

Instance Method Details

#add(*paths) ⇒ Object



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
# File 'lib/ragdoll/cli.rb', line 292

def add(*paths)
  if paths.empty?
    puts 'Error: No paths provided'
    puts 'Usage: ragdoll add PATH [PATH2] [PATH3]... [OPTIONS]'
    puts 'Examples:'
    puts '  ragdoll add file.pdf'
    puts '  ragdoll add ../docs'
    puts '  ragdoll add ../docs/**/*.md'
    puts '  ragdoll add file1.txt file2.pdf ../docs'
    puts '  ragdoll add file.pdf --force-duplicate    # Force add even if duplicate'
    puts '  ragdoll add ../docs --type=pdf            # Only process PDF files'
    puts '  ragdoll add ../docs --skip-confirmation   # Skip prompts'
    exit 1
  end

  client = StandaloneClient.new
  all_results = []

  # First pass: collect all files to process
  all_files = []
  paths.each do |path|
    if path.include?('*') || path.include?('?')
      all_files.concat(collect_files_from_glob(path, options))
    elsif File.directory?(path)
      all_files.concat(collect_files_from_directory(path, options))
    elsif File.file?(path)
      all_files << path
    else
      puts "Warning: Path not found or not accessible: #{path}"
    end
  end

  if all_files.empty?
    puts "No files found to process."
    return
  end

  # Initialize progress bar
  progressbar = ProgressBar.create(
    title: "Adding documents",
    total: all_files.length,
    format: "%t: |%B| %p%% (%c/%C) %e %f"
  )

  # Second pass: process each file with progress
  all_files.each do |file_path|
    progressbar.log "Processing: #{File.basename(file_path)}"
    result = process_single_file(client, file_path, options)
    all_results << result
    progressbar.increment
  end

  progressbar.finish

  # Summary with duplicate detection information
  success_count = all_results.count { |r| r && r[:status] == 'success' }
  error_count = all_results.count { |r| r && r[:status] == 'error' }
  duplicate_count = all_results.count { |r| r && r[:status] == 'success' && r[:duplicate] }
  new_count = success_count - duplicate_count

  puts "\nCompleted:"
  puts "  Successfully processed: #{success_count} files"
  puts "    New documents: #{new_count}"
  puts "    Duplicates #{options[:force_duplicate] ? 'forced' : 'detected'}: #{duplicate_count}" if duplicate_count > 0
  puts "  Errors: #{error_count} files"

  if error_count > 0
    puts "\nErrors:"
    all_results.select { |r| r && r[:status] == 'error' }.each do |result|
      puts "  #{result[:file]}: #{result[:error] || result[:message]}"
    end
  end

  return unless success_count > 0

  # Show new documents
  new_documents = all_results.select { |r| r && r[:status] == 'success' && !r[:duplicate] }
  if new_documents.any?
    puts "\nNew documents added:"
    new_documents.each do |result|
      puts "  #{result[:file]} (ID: #{result[:document_id]})"
      puts "    #{result[:message]}" if result[:message]
    end
  end

  # Show duplicate information
  duplicate_documents = all_results.select { |r| r && r[:status] == 'success' && r[:duplicate] }
  if duplicate_documents.any?
    if options[:force_duplicate]
      puts "\nDuplicates forced to be added:"
      duplicate_documents.each do |result|
        puts "  #{result[:file]} (ID: #{result[:document_id]})"
        puts "    #{result[:message]}" if result[:message]
      end
    else
      puts "\nDuplicates detected (skipped):"
      duplicate_documents.each do |result|
        puts "  #{result[:file]} (existing ID: #{result[:document_id]})"
        puts "    #{result[:message]}" if result[:message]
      end
      puts "\nTip: Use --force-duplicate (-f) to force adding duplicates"
    end
  end

  puts "\nNote: Documents are being processed in the background."
  puts "Use 'ragdoll status <id>' to check processing status."
end

#cleanup_searchesObject



568
569
570
571
572
# File 'lib/ragdoll/cli.rb', line 568

def cleanup_searches
  analytics = Analytics.new
  analytics.options = options
  analytics.cleanup
end

#context(query) ⇒ Object



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/ragdoll/cli.rb', line 487

def context(query)
  client = StandaloneClient.new
  context_options = { limit: options[:limit] }
  context_options[:threshold] = options[:threshold] if options[:threshold]
  ctx = client.get_context(query, **context_options)
  
  # Check if no context was found and provide enhanced feedback
  if ctx[:context_chunks].empty?
    # Get the underlying search response for statistics
    search_response = client.search(query, **context_options)
    display_no_results_feedback(query, search_response, 'context')
  else
    puts JSON.pretty_generate(ctx)
  end
end

#delete(document_id) ⇒ Object



480
481
482
# File 'lib/ragdoll/cli.rb', line 480

def delete(document_id)
  Delete.new.call(document_id, options)
end

#enhance(prompt) ⇒ Object



506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/ragdoll/cli.rb', line 506

def enhance(prompt)
  client = StandaloneClient.new
  enhance_options = { context_limit: options[:limit] }
  enhance_options[:threshold] = options[:threshold] if options[:threshold]
  enhanced = client.enhance_prompt(prompt, **enhance_options)
  
  # Check if no context was found and provide enhanced feedback
  if enhanced[:context_count] == 0
    # Get the underlying search response for statistics
    search_response = client.search(prompt, limit: enhance_options[:context_limit], threshold: enhance_options[:threshold])
    display_no_results_feedback(prompt, search_response, 'enhance')
  else
    puts enhanced[:enhanced_prompt]
  end
end

#healthObject



198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/ragdoll/cli.rb', line 198

def health
  client = StandaloneClient.new

  if client.healthy?
    puts '✓ System is healthy'
    puts '✓ Database connection: OK'
    puts '✓ Configuration: OK'
  else
    puts '✗ System health check failed'
    exit 1
  end
end

#initObject



34
35
36
# File 'lib/ragdoll/cli.rb', line 34

def init
  Config.new.init
end

#listObject



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
# File 'lib/ragdoll/cli.rb', line 220

def list
  client = StandaloneClient.new
  
  # Handle keyword filtering if provided
  if options[:keywords]
    keywords_array = options[:keywords].split(',').map(&:strip)
    search_method = options[:keywords_all] ? :search_by_keywords_all : :search_by_keywords
    documents = client.public_send(search_method, keywords_array, limit: options[:limit])
    
    puts "Listing documents with keywords: #{keywords_array.join(', ')}"
    puts "Mode: #{options[:keywords_all] ? 'ALL keywords (AND)' : 'ANY keywords (OR)'}"
    puts
  else
    documents = client.list_documents(limit: options[:limit])
  end

  # Get accurate embeddings count for all documents
  documents.each do |doc|
    begin
      status_info = client.document_status(doc[:id] || doc['id'])
      doc[:embeddings_count] = status_info[:embeddings_count]
    rescue
      # Keep original count if status fails
    end
  end

  case options[:format]
  when 'json'
    puts JSON.pretty_generate(documents)
  when 'plain'
    documents.each do |doc|
      puts "#{doc[:id]}: #{doc[:title] || 'Untitled'}"
    end
  else
    # Table format - show keywords if keyword filtering is being used
    if options[:keywords]
      puts 'ID'.ljust(10) + 'Title'.ljust(30) + 'Keywords'.ljust(35) + 'Status'.ljust(10) + 'Emb'
      puts '-' * 90
      documents.each do |doc|
        id = (doc[:id] || doc['id'] || '')[0..9].ljust(10)
        title = (doc[:title] || doc['title'] || 'Untitled')[0..29].ljust(30)
        keywords = (doc[:keywords] || doc['keywords'] || []).join(', ')[0..34].ljust(35)
        status = (doc[:status] || doc['status'] || 'unknown')[0..9].ljust(10)
        embeddings = (doc[:embeddings_count] || doc['embeddings_count'] || 0).to_s

        puts "#{id}#{title}#{keywords}#{status}#{embeddings}"
      end
    else
      puts 'ID'.ljust(10) + 'Title'.ljust(40) + 'Status'.ljust(12) + 'Embeddings'
      puts '-' * 80
      documents.each do |doc|
        id = (doc[:id] || doc['id'] || '')[0..9].ljust(10)
        title = (doc[:title] || doc['title'] || 'Untitled')[0..39].ljust(40)
        status = (doc[:status] || doc['status'] || 'unknown')[0..11].ljust(12)
        embeddings = (doc[:embeddings_count] || doc['embeddings_count'] || 0).to_s

        puts "#{id}#{title}#{status}#{embeddings}"
      end
    end
  end
end

#search(query) ⇒ Object



68
69
70
# File 'lib/ragdoll/cli.rb', line 68

def search(query)
  Search.new.call(query, options)
end

#search_historyObject



531
532
533
534
535
# File 'lib/ragdoll/cli.rb', line 531

def search_history
  analytics = Analytics.new
  analytics.options = options
  analytics.history
end

#search_statsObject



542
543
544
545
546
# File 'lib/ragdoll/cli.rb', line 542

def search_stats
  analytics = Analytics.new
  analytics.options = options
  analytics.overview
end

#show(document_id) ⇒ Object



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
# File 'lib/ragdoll/cli.rb', line 157

def show(document_id)
  client = StandaloneClient.new

  begin
    document = client.get_document(document_id)

    case options[:format]
    when 'json'
      puts JSON.pretty_generate(document)
    else
      puts "Document Details for ID: #{document_id}"
      puts "  Title: #{document[:title]}"
      puts "  Status: #{document[:status]}"
      puts "  Embeddings Count: #{document[:embeddings_count]}"
      puts "  Content Length: #{document[:content_length]} characters"
      
      # Show keywords prominently
      keywords = document[:keywords] || document['keywords'] || []
      if keywords.any?
        puts "  Keywords: #{keywords.join(', ')}"
      else
        puts "  Keywords: (none)"
      end
      
      puts "  Created: #{document[:created_at]}"
      puts "  Updated: #{document[:updated_at]}"

      if document[:metadata] && document[:metadata].any?
        puts "\nMetadata:"
        document[:metadata].each do |key, value|
          next if key == 'keywords' # Already displayed above
          puts "  #{key}: #{value}"
        end
      end
    end
  rescue StandardError => e
    puts "Error getting document: #{e.message}"
  end
end

#statsObject



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
# File 'lib/ragdoll/cli.rb', line 82

def stats
  client = StandaloneClient.new
  stats = client.stats

  puts 'System Statistics:'
  puts "  Total documents: #{stats[:total_documents]}"
  puts "  Total embeddings: #{stats[:total_embeddings]}"
  puts "  Storage type: #{stats[:storage_type] || 'unknown'}"

  if stats[:by_status]
    puts "  Documents by status:"
    stats[:by_status].each do |status, count|
      puts "    #{status}: #{count}"
    end
  end

  if stats[:by_type]
    puts "  Documents by type:"
    stats[:by_type].each do |type, count|
      puts "    #{type}: #{count}"
    end
  end

  if stats[:content_types]
    puts "\nContent Types:"
    stats[:content_types].each do |type, count|
      puts "  #{type}: #{count}"
    end
  end

  # Add search analytics if available
  begin
    search_analytics = client.search_analytics(days: 30)
    if search_analytics && !search_analytics.empty?
      puts "\nSearch Analytics (last 30 days):"
      puts "  Total searches: #{search_analytics[:total_searches] || 0}"
      puts "  Unique queries: #{search_analytics[:unique_queries] || 0}"
      puts "  Avg results per search: #{search_analytics[:avg_results_per_search] || 0}"
      puts "  Avg execution time: #{search_analytics[:avg_execution_time] || 0}ms"
      
      if search_analytics[:search_types]
        puts "  Search types:"
        search_analytics[:search_types].each do |type, count|
          puts "    #{type}: #{count}"
        end
      end
      
      puts "  Searches with results: #{search_analytics[:searches_with_results] || 0}"
      puts "  Avg click-through rate: #{search_analytics[:avg_click_through_rate] || 0}%"
    end
  rescue StandardError => e
    # Search analytics not available - silently continue
    puts "\nSearch analytics: Not available (#{e.message})"
  end
end

#status(document_id) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/ragdoll/cli.rb', line 139

def status(document_id)
  client = StandaloneClient.new

  begin
    status = client.document_status(document_id)
    puts "Document Status for ID: #{document_id}"
    puts "  Status: #{status[:status]}"
    puts "  Embeddings Count: #{status[:embeddings_count]}"
    puts "  Embeddings Ready: #{status[:embeddings_ready] ? 'Yes' : 'No'}"
    puts "  Message: #{status[:message]}"
  rescue StandardError => e
    puts "Error getting document status: #{e.message}"
  end
end


555
556
557
558
559
# File 'lib/ragdoll/cli.rb', line 555

def trending
  analytics = Analytics.new
  analytics.options = options
  analytics.trending
end

#update(document_id) ⇒ Object



474
475
476
# File 'lib/ragdoll/cli.rb', line 474

def update(document_id)
  Update.new.call(document_id, options)
end

#versionObject



29
30
31
# File 'lib/ragdoll/cli.rb', line 29

def version
  puts Ragdoll.version.join("\n")
end