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

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