aireview 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,284 @@
1
+ # frozen_string_literal: true
2
+ require 'json'
3
+ require 'uri'
4
+ require_relative 'errors'
5
+ require_relative 'review_comment_formatter'
6
+ require_relative 'utils'
7
+
8
+ module Aireview
9
+ # GitHub pull requests in the shapes the rest of the review knows from
10
+ # GitLab: the merge request hash, change hashes with old/new paths and a
11
+ # diff, notes with an author id. Method names follow GitlabClient, so the
12
+ # CLI and the publisher do not care which platform answers.
13
+ class GithubClient
14
+ # A 403: for /user it means the token has no user to read.
15
+ class ForbiddenError < ApiError; end
16
+
17
+ OPEN_TIMEOUT = 10
18
+ READ_TIMEOUT = 30
19
+ PER_PAGE = 100
20
+ # The files endpoint stops at 3000 files (30 pages); comments have no
21
+ # such cap. Past the limit the walk fails instead of stopping: with an
22
+ # incomplete comment list the publisher would not find its own review
23
+ # and would post a second one.
24
+ PAGE_LIMIT = 100
25
+ REDIRECT_LIMIT = 5
26
+ REDIRECT_STATUSES = [301, 302, 307, 308].freeze
27
+ # GitHub limits issue and PR comment bodies to 65,536 characters.
28
+ MAX_COMMENT_LENGTH = 65_536
29
+ API_VERSION = '2022-11-28'
30
+ GITHUB_COM_API = 'https://api.github.com'
31
+
32
+ # github.com has its API on a separate host, GitHub Enterprise under /api/v3.
33
+ def self.api_url_for(base_url)
34
+ host = URI.parse(base_url).host
35
+ %w[github.com www.github.com].include?(host) ? GITHUB_COM_API : "#{base_url}/api/v3"
36
+ end
37
+
38
+ def initialize(api_url:, token:, review_author: nil, logger: Logger.new($stderr), connection: nil)
39
+ require 'faraday'
40
+
41
+ raise ConfigError, 'GitHub API URL is required' if Aireview::Utils.blank?(api_url)
42
+ raise ConfigError, 'GitHub token is required' if Aireview::Utils.blank?(token)
43
+
44
+ @logger = logger
45
+ @token = token
46
+ @review_author = review_author
47
+ @base_uri = URI.parse("#{api_url.chomp('/')}/")
48
+ @connection = connection || build_connection(api_url)
49
+ end
50
+
51
+ # diff_refs carries the merge base — the same meaning as GitLab's
52
+ # diff_refs.base_sha. The PR diff is taken against it, and it can move
53
+ # while the head stays: when the base branch takes in part of the PR's
54
+ # history. The compare goes against the base branch as it is now, not
55
+ # against base.sha.
56
+ def fetch_merge_request(repo, number)
57
+ pull = get_json("repos/#{repo}/pulls/#{number}")
58
+ validate_pull!(pull)
59
+ head_sha = pull.dig('head', 'sha')
60
+ base_ref = pull.dig('base', 'ref')
61
+ compare = get_json("repos/#{repo}/compare/#{escape_ref(base_ref)}...#{head_sha}", per_page: 1)
62
+ merge_base = compare.dig('merge_base_commit', 'sha') if compare.is_a?(Hash)
63
+ raise ApiError, 'GitHub did not return the merge base of the pull request' if Aireview::Utils.blank?(merge_base)
64
+
65
+ {
66
+ 'title' => pull['title'],
67
+ 'description' => pull['body'],
68
+ 'author' => {'name' => pull.dig('user', 'login')},
69
+ 'source_branch' => pull.dig('head', 'ref'),
70
+ 'target_branch' => base_ref,
71
+ 'sha' => head_sha,
72
+ 'diff_refs' => {'base_sha' => merge_base, 'head_sha' => head_sha},
73
+ 'changed_files' => pull['changed_files']
74
+ }
75
+ end
76
+
77
+ def fetch_merge_request_changes(repo, number)
78
+ get_pages("repos/#{repo}/pulls/#{number}/files", 'files').map { |file| change(file) }
79
+ end
80
+
81
+ # PR conversation comments are issue comments in the GitHub API. They
82
+ # come oldest first; the publisher expects newest first, like GitLab
83
+ # notes sorted by creation time descending.
84
+ def fetch_merge_request_notes(repo, number)
85
+ get_pages("repos/#{repo}/issues/#{number}/comments", 'comments').reverse.map do |comment|
86
+ {
87
+ 'id' => comment['id'],
88
+ 'body' => comment['body'],
89
+ 'author' => {'id' => comment.dig('user', 'login')},
90
+ 'system' => false
91
+ }
92
+ end
93
+ end
94
+
95
+ def post_merge_request_note(repo, number, body)
96
+ send_json(:post, "repos/#{repo}/issues/#{number}/comments", body: fit_comment_body(body))
97
+ end
98
+
99
+ def update_merge_request_note(repo, _number, comment_id, body)
100
+ send_json(:patch, "repos/#{repo}/issues/comments/#{comment_id}", body: fit_comment_body(body))
101
+ end
102
+
103
+ # The login is the author id the publisher matches comments by. A token
104
+ # that cannot read /user (the Actions GITHUB_TOKEN, a GitHub App
105
+ # installation token) needs the login given explicitly: inside Actions a
106
+ # workflow may comment as its own App, so github-actions[bot] is not
107
+ # guessed — a wrong guess would miss the review and post a duplicate.
108
+ def fetch_current_user
109
+ return {'id' => @review_author} if Aireview::Utils.present?(@review_author)
110
+
111
+ {'id' => get_json('user')['login']}
112
+ rescue ForbiddenError => e
113
+ raise ApiError, 'GitHub token cannot read its user; set GITHUB_REVIEW_AUTHOR to the login that posts ' \
114
+ "the comments (github-actions[bot] for the Actions GITHUB_TOKEN). #{e.message}"
115
+ end
116
+
117
+ private
118
+
119
+ def validate_pull!(pull)
120
+ valid = pull.is_a?(Hash) && %w[head base].all? { |side| pull[side].is_a?(Hash) } &&
121
+ Aireview::Utils.present?(pull.dig('head', 'sha')) && Aireview::Utils.present?(pull.dig('base', 'ref'))
122
+ raise ApiError, 'GitHub API returned an invalid pull request payload' unless valid
123
+ end
124
+
125
+ # A file without a patch is a binary or a diff too large for GitHub; it
126
+ # has no mode fields either. Only a rename without changes explains an
127
+ # empty diff, everything else counts as unavailable — the report must not
128
+ # claim that a binary was reviewed. An empty new file ends up there too.
129
+ # Note: Git does not track line counts for binary files, so a binary file
130
+ # renamed with byte modifications also reports changes == 0 without a patch;
131
+ # without a base blob comparison this is indistinguishable from a pure rename.
132
+ def change(file)
133
+ status = file['status']
134
+ patch = file['patch'].to_s
135
+ pure_rename = status == 'renamed' && file['changes'].to_i.zero?
136
+ {
137
+ 'old_path' => file['previous_filename'] || file['filename'],
138
+ 'new_path' => file['filename'],
139
+ 'diff' => patch,
140
+ 'new_file' => status == 'added',
141
+ 'deleted_file' => status == 'removed',
142
+ 'renamed_file' => status == 'renamed',
143
+ 'too_large' => patch.empty? && !pure_rename
144
+ }
145
+ end
146
+
147
+ # Pages are followed by the Link header, not counted: GitHub decides
148
+ # where the list ends.
149
+ def get_pages(path, what)
150
+ items = []
151
+ url = path
152
+ params = {per_page: PER_PAGE}
153
+
154
+ PAGE_LIMIT.times do
155
+ response = request(:get, url, params: params)
156
+ batch = parse_json(response)
157
+ raise ApiError, "GitHub API returned an invalid #{what} list" unless batch.is_a?(Array)
158
+
159
+ items.concat(batch)
160
+ url = next_page(response)
161
+ return items unless url
162
+
163
+ params = {}
164
+ end
165
+
166
+ raise ApiError, "Pull request has more than #{PAGE_LIMIT * PER_PAGE} #{what}"
167
+ end
168
+
169
+ def next_page(response)
170
+ link = response.headers['link'].to_s
171
+ link.split(',').each do |part|
172
+ match = /<([^>]+)>\s*;\s*rel="next"/.match(part)
173
+ return match[1] if match
174
+ end
175
+ nil
176
+ end
177
+
178
+ # Branch names may hold characters that mean something in a URL; the
179
+ # slashes of a branch name stay, GitHub reads them as part of the ref.
180
+ def escape_ref(ref)
181
+ ref.split('/').map { |part| URI.encode_www_form_component(part).gsub('+', '%20') }.join('/')
182
+ end
183
+
184
+ def build_connection(api_url)
185
+ Faraday.new(url: "#{api_url.chomp('/')}/") do |builder|
186
+ builder.request :json
187
+ builder.options.open_timeout = OPEN_TIMEOUT
188
+ builder.options.timeout = READ_TIMEOUT
189
+ builder.adapter Faraday.default_adapter
190
+ end
191
+ end
192
+
193
+ def get_json(path, params = {})
194
+ parse_json(request(:get, path, params: params))
195
+ end
196
+
197
+ def request(method, path, params: nil, body: nil)
198
+ current_path = path
199
+ current_params = params
200
+ redirects = 0
201
+
202
+ loop do
203
+ response = execute_request(method, current_path, current_params, body)
204
+ return response unless REDIRECT_STATUSES.include?(response.status.to_i)
205
+
206
+ redirects += 1
207
+ raise ApiError, 'Too many redirects from GitHub API' if redirects > REDIRECT_LIMIT
208
+
209
+ current_path, current_params = follow_redirect(response, current_path, current_params)
210
+ end
211
+ rescue Faraday::Error => e
212
+ raise ApiError, "GitHub API request failed: #{e.message}"
213
+ end
214
+
215
+ def send_json(method, path, body)
216
+ parse_json(request(method, path, body: body))
217
+ end
218
+
219
+ def execute_request(method, path, params, body)
220
+ if body.nil?
221
+ @connection.public_send(method, path, params, headers)
222
+ else
223
+ @connection.public_send(method, path) do |request|
224
+ request.headers.update(headers)
225
+ request.body = JSON.generate(body)
226
+ end
227
+ end
228
+ end
229
+
230
+ def parse_json(response)
231
+ status = response.status.to_i
232
+ body = response.body.to_s
233
+
234
+ return JSON.parse(body) if status.between?(200, 299)
235
+ raise ForbiddenError, "GitHub API error #{status}: #{body}" if status == 403
236
+
237
+ raise ApiError, "GitHub API error #{status}: #{body}"
238
+ rescue JSON::ParserError
239
+ raise ApiError, "GitHub API returned invalid JSON: #{body}"
240
+ end
241
+
242
+ def headers
243
+ {
244
+ 'Accept' => 'application/vnd.github+json',
245
+ 'Authorization' => "Bearer #{@token}",
246
+ 'Content-Type' => 'application/json',
247
+ 'X-GitHub-Api-Version' => API_VERSION
248
+ }
249
+ end
250
+
251
+ # Follow same-origin redirects (e.g. repo rename or transfer) without
252
+ # leaking authorization tokens to external hosts.
253
+ def follow_redirect(response, current_path, current_params)
254
+ location = response.headers['location'].to_s
255
+ if Aireview::Utils.blank?(location)
256
+ raise ApiError, "GitHub API redirected with status #{response.status} without a Location header"
257
+ end
258
+
259
+ current_url = URI.join(@base_uri.to_s, current_path)
260
+ target = URI.join(current_url.to_s, location)
261
+ unless same_origin?(target, @base_uri)
262
+ raise ApiError, "Refusing redirect from #{@base_uri.host} to #{target.host}"
263
+ end
264
+
265
+ [target.to_s, target.query ? {} : current_params]
266
+ end
267
+
268
+ def same_origin?(target, base)
269
+ target.scheme == base.scheme && target.host == base.host && target.port == base.port
270
+ end
271
+
272
+ # When an enormous review overflows GitHub's 65,536-char limit, findings
273
+ # and summary stay intact; only the files list in the not-reviewed block
274
+ # (or the summary if oversized) is shortened with a note. Never drops
275
+ # findings or result: a corrupted review must not be saved to GitHub.
276
+ def fit_comment_body(body, limit = MAX_COMMENT_LENGTH)
277
+ fitted = ReviewCommentFormatter.fit(body, limit: limit)
278
+ return fitted if fitted
279
+
280
+ raise ApiError, "Review comment exceeds GitHub limit of #{limit} characters " \
281
+ 'and cannot be shortened without dropping findings'
282
+ end
283
+ end
284
+ end
@@ -13,7 +13,7 @@ module Aireview
13
13
  class JevStage
14
14
  # The report line: :jev (Jev decided everything), :jev_partial (some
15
15
  # went to the LLM), :jev_failed (the LLM decided everything).
16
- Outcome = Struct.new(:accepted, :note, keyword_init: true)
16
+ Outcome = Struct.new(:accepted, :note, :model, keyword_init: true)
17
17
 
18
18
  def initialize(config:, critic:, logger: Logger.new($stderr))
19
19
  @config = config
@@ -37,11 +37,28 @@ module Aireview
37
37
  accepted = drop_duplicates(in_generate_order(accepted, candidates), result.answers)
38
38
  @logger.info("Pipeline critique pass completed with #{accepted.size} kept candidate(s) (engine=jev, " \
39
39
  "model=#{result.model}, requests=#{result.requests})")
40
- Outcome.new(accepted: accepted, note: unverifiable.empty? || fail? ? :jev : :jev_partial)
40
+ Outcome.new(accepted: accepted, note: outcome_note(unverifiable, candidates, result.model),
41
+ model: outcome_model(result.model))
41
42
  end
42
43
 
43
44
  private
44
45
 
46
+ def outcome_note(unverifiable, candidates, answered_model)
47
+ if unverifiable.empty? || fail?
48
+ Aireview::Utils.present?(answered_model) ? :jev : nil
49
+ elsif unverifiable.size == candidates.size && Aireview::Utils.blank?(answered_model)
50
+ :jev_failed
51
+ else
52
+ :jev_partial
53
+ end
54
+ end
55
+
56
+ def outcome_model(answered_model)
57
+ return "jev/#{answered_model}" if Aireview::Utils.present?(answered_model)
58
+
59
+ :critique_no_verdicts if fail?
60
+ end
61
+
45
62
  def fail?
46
63
  @config.jev_fallback == 'fail'
47
64
  end
@@ -17,6 +17,16 @@ module Aireview
17
17
  end
18
18
  end
19
19
 
20
+ # RubyLLM 2 sends the temperature as given, while 1.x replaced it with
21
+ # 1.0 for OpenAI reasoning models (o1, o3, gpt-5…) and dropped it for the
22
+ # search ones (gpt-4o-search-preview…), which take no other: such a
23
+ # request is a BadRequest, fatal for the router, and the stage would not
24
+ # even reach a fallback model. The RubyLLM registry knows which models
25
+ # take a temperature; where it does not (a server of your own,
26
+ # assume_model_exists, search models with an empty flag) the name
27
+ # decides, as in 1.x.
28
+ NO_TEMPERATURE_MODELS = %r{\A(?:openai/)?(?:o\d|gpt-5)|-search}
29
+
20
30
  def initialize(config:, logger: Logger.new($stderr))
21
31
  @config = config
22
32
  @logger = logger
@@ -25,17 +35,11 @@ module Aireview
25
35
 
26
36
  # Returns the RubyLLM answer; read it with LlmClient.content. A request
27
37
  # error is re-raised as is — LlmFailure classifies it.
28
- def request(prompt, candidate:, key:, timeout:, key_index: 0)
29
- load_ruby_llm
38
+ def request(prompt, candidate:, key:, timeout:)
30
39
  stage = prompt.stage.to_s
31
40
  model = candidate.model
32
- @logger.info("LLM #{stage} request started (model=#{model}, temperature=#{prompt.temperature})")
33
- chat = build_chat(context: context(stage, candidate, key, key_index), stage: stage,
34
- model: model, provider: candidate.provider)
35
- chat = configure_reasoning(chat: chat, model: model, provider: candidate.provider)
36
- .with_temperature(prompt.temperature.to_f)
37
- .with_schema(prompt.schema)
38
- chat.with_instructions(prompt.system)
41
+ chat = prepare(prompt, candidate: candidate, key: key)
42
+ @logger.info("LLM #{stage} request started (model=#{model}, temperature=#{chat.temperature || 'model default'})")
39
43
  response = Timeout.timeout(timeout) { chat.ask(prompt.user) }
40
44
  @logger.info("LLM #{stage} request completed (model=#{model}#{token_counts(response)})")
41
45
  response
@@ -44,6 +48,21 @@ module Aireview
44
48
  raise
45
49
  end
46
50
 
51
+ # The request as it will go, without sending it: the chat with the model,
52
+ # key, schema, instructions and temperature set. chat.render builds it —
53
+ # that is how the specs check the real request without the network.
54
+ def prepare(prompt, candidate:, key:)
55
+ load_ruby_llm
56
+ stage = prompt.stage.to_s
57
+ chat = build_chat(context: context(stage, candidate, key), stage: stage,
58
+ model: candidate.model, provider: candidate.provider)
59
+ chat = configure_reasoning(chat: chat, model: candidate.model, provider: candidate.provider)
60
+ .with_temperature(temperature_for(chat, prompt, candidate))
61
+ .with_schema(prompt.schema)
62
+ chat.with_instructions(prompt.system)
63
+ chat
64
+ end
65
+
47
66
  # The answer as RubyLLM 1.x gave it under a schema: the parsed JSON when
48
67
  # the text is JSON, the text itself otherwise (the pipeline repairs it).
49
68
  # RubyLLM 2 always returns the text, and a Hash that breaks the schema
@@ -82,6 +101,14 @@ module Aireview
82
101
  raise ConfigError, "Missing dependency: #{e.message}"
83
102
  end
84
103
 
104
+ # The temperature for a model that takes one (see NO_TEMPERATURE_MODELS);
105
+ # nil — its own default, left out of the request.
106
+ def temperature_for(chat, prompt, candidate)
107
+ accepts = chat.model.metadata[:temperature] if chat.model.respond_to?(:metadata)
108
+ accepts = !candidate.model.to_s.match?(NO_TEMPERATURE_MODELS) if accepts.nil?
109
+ accepts ? prompt.temperature.to_f : nil
110
+ end
111
+
85
112
  def configure_reasoning(chat:, model:, provider:)
86
113
  return chat unless provider == 'ollama' && model.start_with?('gpt-oss:')
87
114
 
@@ -99,11 +126,10 @@ module Aireview
99
126
  context.chat(model: model, provider: provider.to_sym, assume_model_exists: true)
100
127
  end
101
128
 
102
- # A RubyLLM context per stage, key source (a provider's API or a server
103
- # of your own) and key index: switching the key is another context, not
104
- # an edit of the global config.
105
- def context(stage, candidate, key, key_index)
106
- @contexts[[stage, candidate.key_source, key_index]] ||= build_context(candidate, key)
129
+ # A RubyLLM context per stage and key source (a provider's API or a server
130
+ # of your own): isolated from the global config.
131
+ def context(stage, candidate, key)
132
+ @contexts[[stage, candidate.key_source]] ||= build_context(candidate, key)
107
133
  end
108
134
 
109
135
  def build_context(candidate, api_key)