Class: Commiti::MessageGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/services/message_generator.rb

Constant Summary collapse

COMMIT_PREFIX_ERROR =
'First line must start with a conventional commit type (feat:, fix:, etc.).'
DEFAULT_COMMIT_SUBJECT =
'update project files'
COMMIT_PREFIX_PATTERN =
/\A(feat|fix|chore|refactor|docs|style|test|perf|ci|build|revert)(\([^)]+\))?!?\s*:?\s*/i

Instance Method Summary collapse

Constructor Details

#initialize(flow_type:, run_stage:) ⇒ MessageGenerator

Returns a new instance of MessageGenerator.



9
10
11
12
# File 'lib/services/message_generator.rb', line 9

def initialize(flow_type:, run_stage:)
  @flow_type = flow_type
  @run_stage = run_stage
end

Instance Method Details

#generate_candidates(client:, prompt:, diff_metadata:, count:, model:) ⇒ Object



14
15
16
17
18
19
# File 'lib/services/message_generator.rb', line 14

def generate_candidates(client:, prompt:, diff_metadata:, count:, model:)
  (1..count).map do |index|
    puts "\nGenerating candidate #{index}/#{count}..."
    generate_with_quality_check(client: client, prompt: prompt, diff_metadata: , model: model)
  end
end

#generate_with_quality_check(client:, prompt:, diff_metadata:, model:) ⇒ Object



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
# File 'lib/services/message_generator.rb', line 21

def generate_with_quality_check(client:, prompt:, diff_metadata:, model:)
  raw = run_stage.call("Generating #{flow_type} with Google AI") do
    client.generate(
      system: prompt[:system],
      user: prompt[:user],
      model: model,
      timeout_seconds: 300,
      open_timeout_seconds: 10
    )
  end

  message = clean_output(raw)
  reason = invalid_generation_reason(message: message, diff_metadata: )
  return message if reason.nil?

  puts "\nGenerated output looked weak: #{reason}"
  puts "Retrying once with stronger constraints...\n"

  retry_user = <<~MSG
    #{prompt[:user].rstrip}

    Your previous draft was invalid: #{reason}
    Rewrite from scratch using only the provided diff content.
    Do not claim there were no changes if files were changed.
  MSG

  retried = run_stage.call("Regenerating #{flow_type} with stricter prompt") do
    client.generate(
      system: prompt[:system],
      user: retry_user,
      model: model,
      timeout_seconds: 300,
      open_timeout_seconds: 10
    )
  end

  retried_message = clean_output(retried)
  retry_reason = invalid_generation_reason(message: retried_message, diff_metadata: )
  return retried_message if retry_reason.nil?

  if flow_type == :commit
    normalized_commit = normalize_commit_with_prefix(retried_message, diff_metadata: )
    return normalized_commit unless normalized_commit.nil?
  end

  raise "Generated #{flow_type} is still invalid after retry: #{retry_reason}"
end