CPAN/Maker/Bootstrapper/Role/LLM/Reviewer.pm untested

filter: Statementstmt 0.0% 0 / 251 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 70 MC/DCmcdc 0.0% 0 / 39 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 475 CC 42 SCAR 44.1
CC
42
Cov
0%
_cmd_review
272.0
cmd_code_finding
56.0
_get_review_prompt
30.0
CRAP 82.5
1 package CPAN::Maker::Bootstrapper::Role::LLM::Reviewer;
2  
3 use strict;
4 use warnings;
5  
6 use open ':std', ':encoding(UTF-8)';
7  
8 use CLI::Simple::Constants qw(:booleans);
9 use CLI::Simple::Utils qw(slurp);
10 use CPAN::Maker::Bootstrapper::Constants qw(:all);
11 use Cwd qw(getcwd abs_path);
12 use Data::Dumper;
13 use English qw(-no_match_vars);
14 use File::Basename qw(basename);
15 use File::Copy qw(copy);
16 use File::Find;
17 use File::Path qw(make_path);
18 use Role::Tiny;
19 use JSON;
20  
21 ########################################################################
22 sub _get_review_prompt {
23 ########################################################################
24 my ( $self, $review_type, $review ) = @_;
25  
26 if ( !-d '.prompts' || !-e ".prompts/$review_type-review.prompt" ) {
27 $self->_install_prompts;
28 }
29  
30 my @prompts = ( $self->get_prompt // ".prompts/$review_type-review.prompt" );
31 my @profiles
32 = $review && !$self->get_prompt_profile ? @{ $review->{prompt_profiles} // [] } : @{ $self->get_prompt_profile // [] };
33  
34 push @prompts, map {".prompts/$_.prompt"} @profiles;
35  
36 my $prompt = q{};
37  
38 foreach my $f (@prompts) {
39 my $abs_path = abs_path($f)
40 or die "ERROR: $f not found\n";
41  
42 die "ERROR: $f is empty or not found\n"
43 if !-e $abs_path || !-s $abs_path;
44  
45 $prompt .= "\n" . slurp($abs_path);
46 }
47  
48 $prompt =~ s/^#[^\n]*(?:\n|\z)//xsmg;
49 $prompt =~ s/\n{2,}/\n/xsmg; # collapse 2+ blank lines to one
50 $prompt =~ s/\A\n+//xsm; # strip leading blank lines
51  
52 die "ERROR: prompt file prompt is essentially empty\n"
53 if $prompt !~ /\S/xsm;
54  
55 return $prompt;
56 }
57  
58 ########################################################################
59 sub _install_prompts {
60 ########################################################################
61 my ( $self, @prompts ) = @_;
62  
63 make_path('.prompts');
64  
65 if ( !@prompts ) {
66 @prompts = map {"$_-review.prompt"} qw(code pod);
67 }
68  
69 die "ERROR: could not create .prompts directory\n"
70 if !-d '.prompts';
71  
72 my $dist_dir = $self->get_dist_dir;
73  
74 for my $prompt (@prompts) {
75 my $dest = ".prompts/$prompt";
76  
77 next if -e $dest;
78  
79 copy "$dist_dir/$prompt", $dest
80 or die "ERROR: could not install $prompt to .prompts/: $OS_ERROR\n";
81  
82 print "Installed default prompt: $dest\n";
83 }
84  
85 print "\nEdit these files to customize your review prompts.\n";
86 print "Set code-review-prompt or pod-review-prompt in your\n";
87 print "config to use prompts from an explicit path.\n\n";
88  
89 return;
90 }
91  
92 ########################################################################
93 sub _get_latest_review {
94 ########################################################################
95 my ( $self, $file, $review_type ) = @_;
96  
97 my $name = basename($file);
98 $name =~ s/[.]in\z//xsm;
99 $name =~ s/[.][^.]+\z//xsm;
100  
101 my @review_files;
102  
103 find(
104 sub {
105 return if !-f $File::Find::name;
106 return if $_ !~ /^\Q$name\E-review.*[.]\Q$review_type\E$/xsm;
107 push @review_files, $File::Find::name;
108 },
109 getcwd,
110 );
111  
112 my ($review_file) = reverse sort { $a cmp $b } @review_files;
113  
114 return ( undef, undef )
115 if !$review_file;
116  
117 my $content = slurp $review_file;
118  
119 die "ERROR: no content for $review_file\n"
120 if !length $content;
121  
122 my $review = JSON->new->decode($content);
123  
124 return ( $review, $review_file );
125 }
126  
127 ########################################################################
128 sub cmd_pod_finding {
129 ########################################################################
130 my ($self) = @_;
131  
132 $self->_load_ASCIITable;
133  
134 my ($file) = $self->get_args;
135  
136 my ( $review, $review_file ) = $self->_get_latest_review( $file, 'pod' );
137  
138 die "ERROR: no findings for $file\n"
139 if !$review || !$review_file;
140  
141 $self->_show_pod_findings( $review, $review_file );
142  
143 return $SUCCESS;
144 }
145  
146 ########################################################################
147 sub _show_pod_findings {
148 ########################################################################
149 my ( $self, $review, $review_file ) = @_;
150  
151 my $mode = $review->{mode} // 'review';
152 my $findings = $review->{findings} // [];
153  
154 if ( $mode eq 'generate' ) {
155 printf {*STDOUT} "Mode: POD generation\n\n";
156 }
157  
158 my $t = Text::ASCIITable->new( { headingText => "POD Review: $review_file" } );
159  
160 $t->setCols( 'ID', 'Section/Method', 'Severity', 'Description' );
161 $t->setColWidth( 'ID', 4 );
162 $t->setColWidth( 'Section/Method', 30 );
163 $t->setColWidth( 'Severity', 12 );
164 $t->setColWidth( 'Description', 40 );
165  
166 if ( !@{$findings} ) {
167 print {*STDOUT} "No findings.\n\n";
168 return;
169 }
170  
171 foreach my $f ( sort { $a->{id} <=> $b->{id} } @{$findings} ) {
172 my $location = $f->{method} // $f->{section} // '-';
173 my $severity = $f->{severity};
174  
175 $t->addRow( $f->{id}, $location, $severity, $f->{description} );
176 $t->addRow( q{}, q{}, q{}, "\nDetail:\n\n" . $f->{detail} );
177 $t->addRow( q{}, q{}, q{}, "\nSuggestion:\n\n" . $f->{suggestion} );
178 $t->addRowLine;
179 }
180  
181 print {*STDOUT} $t;
182  
183 printf {*STDOUT} "%d finding%s.\n\n", scalar @{$findings}, scalar @{$findings} == 1 ? q{} : 's';
184  
185 return;
186 }
187  
188 ########################################################################
189 sub cmd_code_review {
190 ########################################################################
191 my ($self) = @_;
192  
193 $self->_load_ASCIITable;
194  
195 my ( $file, $api_key ) = $self->get_args;
196  
197 my ( $review, $review_file ) = $self->_get_latest_review( $file, 'code' );
198  
199 die "ERROR: set all disposition statuses before resubmitting a review\n"
200 if !$self->_check_annotation_dispositions($review);
201  
202 my $llm_rsp = $self->_cmd_review(
203 type => 'code',
204 file => $file,
205 review => $review,
206 model => $review && $review->{model} ? $review->{model} : $DEFAULT_CODE_REVIEW_MODEL,
207 api_key => $api_key,
208 context_files => $self->get_context,
209 );
210  
211 return $FAILURE
212 if !$llm_rsp;
213  
214 $self->_print_token_usage( $llm_rsp, 'Code Review: Token Usage Report' );
215  
216 return $SUCCESS;
217 }
218  
219 ########################################################################
220 sub cmd_pod_review {
221 ########################################################################
222 my ($self) = @_;
223  
224 $self->_load_ASCIITable;
225  
226 my ( $file, $api_key ) = $self->get_args;
227  
228 my ( $review, $review_file ) = $self->_get_latest_review( $file, 'pod' );
229  
230 my $llm_rsp = $self->_cmd_review(
231 type => 'pod',
232 file => $file,
233 api_key => $api_key,
234 model => $review && $review->{model} ? $review->{model} : $DEFAULT_POD_REVIEW_MODEL,
235 );
236  
237 return $FAILURE
238 if !$llm_rsp;
239  
240 $self->_print_token_usage( $llm_rsp, 'POD Review: Token Usage Report' );
241  
242 return $SUCCESS;
243 }
244  
245 ########################################################################
246 sub _cmd_review {
247 ########################################################################
248 my ( $self, %args ) = @_;
249  
250 my ( $review_type, $api_key, $default_model ) = @args{qw(type api_key model)};
251  
252 my ( $file, $review, $context_files ) = @args{qw(file review context_files)};
253  
254 my $model = $self->get_model // $default_model;
255  
256 warn sprintf "WARNING: model changed from %s => %s\n", $review->{model}, $model
257 if $review && $review->{model} && $model ne $review->{model};
258  
259 $self->set_model($model);
260  
261 my @context_files = $review && !$context_files ? @{ $review->{context} // [] } : @{ $context_files // [] };
262  
263 foreach my $f ( grep {defined} ( $file, @context_files ) ) {
264 my $abs_path = abs_path($f);
265  
266 die "ERROR: file [$f] not found or empty.\n"
267 if !$abs_path || !-e $abs_path || !-s $abs_path;
268 }
269  
270 my $llm = $self->_check_llm($api_key);
271  
272 my $prompt_str = $self->_get_review_prompt( $review_type, $review );
273  
274 my @prompt;
275  
276 push @prompt, $llm->text($prompt_str);
277  
278 my $text = $review_type eq 'pod' ? slurp( abs_path($file) ) : $self->_strip_pod( slurp( abs_path($file) ) );
279  
280 my $title = $review_type eq 'pod' ? basename($file) : 'primary: ' . basename($file);
281  
282 push @prompt,
283 $llm->document(
284 data => $text,
285 title => $title,
286 );
287  
288 foreach my $f (@context_files) {
289 push @prompt,
290 $llm->document(
291 data => $self->_strip_pod($f),
292 title => 'context:' . basename($f),
293 );
294 }
295  
296 if ($review) {
297 push @prompt,
298 $llm->document(
299 data => JSON->new->utf8->encode($review),
300 title => 'annotations:' . basename($file),
301 );
302 }
303  
304 my ( $input_tokens, $input_cost ) = $llm->count_input_tokens( \@prompt );
305  
306 $self->_pre_submission_report(
307 type => $review_type,
308 prompt => $prompt_str,
309 text => $text,
310 annotations => $review ? JSON->new->utf8->encode($review) : undef,
311 context_files => \@context_files,
312 max_tokens => $self->get_max_tokens,
313 input_tokens => $input_tokens,
314 input_cost => $input_cost,
315 );
316  
317 return $SUCCESS
318 if $self->get_dry_run;
319  
320 my $llm_rsp = $self->_submit_prompt( $llm, \@prompt );
321 my $content = $llm_rsp->content;
322  
323 die "ERROR: no content object returned by LLM\n"
324 if !$content;
325  
326 if ( !$content->text ) {
327 warn "WARNING: LLM did not return any text from request.\n";
328 return;
329 }
330  
331 if ( $llm_rsp->was_cutoff ) {
332 warn "WARNING: response was truncated (hit max_tokens). Increase --max-tokens for a complete response.\n";
333 }
334  
335 my $name = basename($file);
336 $name =~ s/[.].*$//xsm;
337  
338 my ( $sec, $min, $hour, $day, $month, $year ) = localtime;
339 $year += 1900;
340 $month++;
341  
342 my $ts = sprintf '%04d-%02d-%02d-%02d%02d%02d', $year, $month, $day, $hour, $min, $sec;
343  
344 my $review_file = sprintf '%s-review-%s.%s', $name, $ts, $review_type;
345  
346 my $json_text = $content->text;
347 $json_text =~ s/\A\s*```(?:json)?\s*\n?//xsm;
348 $json_text =~ s/\s*```\s*\z//xsm;
349  
350 $review = eval { JSON->new->decode($json_text); };
351  
352 die "ERROR: unable to decode JSON\n$EVAL_ERROR\nresponse was:\n" . $content->text
353 if $EVAL_ERROR;
354  
355 $review->{model} = $self->get_model; # save for next time
356  
357 if ( $review_type eq 'code' ) {
358  
359 if ( $self->get_prompt_profile ) {
360 $review->{prompt_profiles} = $self->get_prompt_profile;
361 }
362  
363 if ( $self->get_context ) {
364 $review->{context} = $self->get_context;
365 }
366 }
367  
368 open my $fh, '>', $review_file
369 or die "ERROR: could not open $review_file for writing.\n$OS_ERROR";
370  
371 print {$fh} JSON->new->utf8->pretty->encode($review);
372  
373 close $fh
374 or warn "WARNING: could not close $review_file: $OS_ERROR";
375  
376 return $llm_rsp;
377 }
378  
379 ########################################################################
380 sub cmd_code_finding {
381 ########################################################################
382 my ($self) = @_;
383  
384 $self->_load_ASCIITable;
385  
386 my ( $file, $finding_id ) = $self->get_args;
387  
388 die "ERROR: file argument is required\n"
389 if !$file;
390  
391 die "ERROR: finding ID is required\n"
392 if !$finding_id;
393  
394 die "ERROR: finding ID must be a positive integer\n"
395 if $finding_id !~ /^\d+$/xsm || $finding_id < 1;
396  
397 die "ERROR: $file not found or inaccessible\n"
398 if !abs_path($file);
399  
400 my ( $review, $review_file ) = $self->_get_latest_review( $file, 'code' );
401  
402 die "ERROR: no review file found for $file\n"
403 if !$review;
404  
405 my ($finding) = grep { $_->{id} == $finding_id } @{ $review->{findings} };
406  
407 die "ERROR: finding $finding_id not found in $review_file\n"
408 if !$finding;
409  
410 my $total = scalar @{ $review->{findings} };
411  
412 my $t = Text::ASCIITable->new( { headingText => sprintf 'Finding %d of %d - %s', $finding_id, $total, $review_file } );
413  
414 $t->setCols( 'Field', 'Value' );
415 $t->setColWidth( 'Field', 16 );
416 $t->setColWidth( 'Value', 56 );
417 $t->alignCol( Value => sub { return sprintf '%-56s', shift; } );
418  
419 $t->addRow( 'ID', $finding->{id} );
420 $t->addRow( 'Function', $finding->{function} );
421 $t->addRow( 'Severity', $finding->{severity} );
422 $t->addRow( 'Disposition', $finding->{disposition} // '-' );
423 $t->addRow( 'Comment', $finding->{comment} // '-' );
424 $t->addRowLine;
425 $t->addRow( 'Description', $finding->{description} );
426 $t->addRowLine;
427 $t->addRow( 'Excerpt', $finding->{excerpt} );
428 $t->addRowLine;
429 $t->addRow( 'Detail', $finding->{detail} );
430  
431 print {*STDOUT} $t;
432  
433 return $SUCCESS;
434 }
435  
436 1;
437  
438 __END__