Module: Sloprb::Typoeater

Defined in:
lib/sloprb/typoeater.rb

Constant Summary collapse

SYSTEM_PROMPT =
<<~PROMPT
  You are a Ruby syntax error fixer. You will be given a Ruby source file that has a syntax error, along with the error message.
  Your job is to fix the syntax error and return the corrected source file.

  Rules:
  - Return ONLY the complete corrected Ruby source file
  - Do not include any explanation, comments about the fix, or markdown formatting
  - Do not change any logic or behavior — only fix the syntax error
  - Preserve all existing comments, whitespace style, and formatting
PROMPT

Class Method Summary collapse

Class Method Details

.call(path, error_context, chat: nil) ⇒ Object



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
# File 'lib/sloprb/typoeater.rb', line 19

def call(path, error_context, chat: nil)
  chat ||= default_chat

  source = File.read(path)

  user_prompt = <<~PROMPT
    Here is the Ruby source file with a syntax error:

    ```ruby
    #{source}
    ```

    Syntax error:
    #{error_context}

    Return the complete corrected Ruby source file.
  PROMPT

  response = chat.with_instructions(SYSTEM_PROMPT).ask(user_prompt)
  corrected = strip_fences(response.content)
  corrected << "\n" unless corrected.end_with?("\n")

  result = Prism.parse(corrected)
  return if result.errors.any?

  corrected
rescue => e
  warn "[sloprb] failed to autocorrect #{path}: #{e.message}" if ENV["SLOPRB_DEBUG"]
  nil
end

.register_hookObject



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

def register_hook
  require "require-hooks/setup"

  RequireHooks.source_transform do |path, source|
    result = Prism.parse_file(path)
    next unless result.errors.any?

    warn "[sloprb] invalid syntax in #{path}, fixing..."

    corrected = Typoeater.call(path, result.errors_format)
    # Let it fail through
    next unless corrected

    File.write(path, corrected)

    warn "[sloprb] auto-corrected syntax error in #{path}"

    corrected
  end
end