blib/lib/App/karr/Foundation/Runner.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« blib/lib/App/karr/Cmd/Unlock.pm ↑ Summary blib/lib/App/karr/Cmd/Delete.pm »
1 # ABSTRACT: karr-foundation command execution -- fork/pipe/select tee + run classification
2  
3 package App::karr::Foundation::Runner;
4 our $VERSION = '0.602';
5 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use App::karr::Error qw( clean_error user_error );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use App::karr::Encoding qw( from_octets json_decode to_octets to_octets_for_env );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use App::karr::AgentName qw( agent_name );
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use Encode ();
10 use IO::Select;
11 use IO::Handle ();
12 use POSIX qw( SIGTERM SIGKILL SIGALRM WNOHANG setpgid );
13 use Scalar::Util qw( looks_like_number );
14  
15  
16  
17 has foundation => (
18 is => 'ro',
19 weak_ref => 1,
20 required => 1,
21 );
22  
23 # ---------------------------------------------------------------------------
24 # Command execution
25 # ---------------------------------------------------------------------------
26  
27 sub _run_command {
28 my ( $self, $repo, $karr, $cmd, $ticket, $agent, %opt ) = @_;
29 my $command = $cmd // $karr->{command};
30 my $stream_terms = $self->foundation->_stream_to_terminal;
31  
32 # What this run is, and how long it may take. Both default to the agent, who
33 # was the only caller for as long as there was only one kind of run. The
34 # C<on_drained> hook (#193) is the second: it wants the whole apparatus below
35 # -- the process group, the timeout, the tee -- and none of the identity, so
36 # it passes its own role and its own budget and takes everything else as it
37 # stands. Anything the identity decides is keyed off $role and nothing else.
38 my $role = $opt{role} // 'agent';
39 my $max_runtime = $opt{max_runtime} // $karr->{max_runtime} // 1800;
40  
41 # How this run's output is to be read for a human, decided by the agent
42 # definition that supplied the command and by nothing else (#188). Undef --
43 # every board that names no agent -- is the historical path: the octets the
44 # command printed, verbatim, to the log and the terminal.
45 my $render = ref $agent eq 'HASH' ? $agent->{render} : undef;
46  
47 # Environment for the child (and all karr calls it spawns). The child inherits
48 # it across the fork/exec below, so a command template — including the
49 # synthesized claude command — expands $PROMPT, ${KARR_REPO}, $KARR_ROLE and
50 # every other variable foundation itself was started with as ordinary shell
51 # parameters. %ENV is a byte boundary owned by App::karr::Encoding, so each
52 # value is encoded through to_octets_for_env before the assignment (#167):
53 # a non-ASCII prompt would otherwise emit "Wide character in setenv" on
54 # stderr and the bytes the child receives would depend on the IO layers in
55 # scope at the call site.
56 local $ENV{KARR_REPO} = to_octets_for_env("$repo");
57 local $ENV{KARR_ROLE} = to_octets_for_env($role);
58  
59 # The prompt is the board agent's instruction, so only the board agent gets
60 # the board's one. A hook handed a prompt telling it to pick the next
61 # actionable task would be told to do the one thing it is not there for, and
62 # every karr write it made would land in the agent's activity log -- which is
63 # the evidence the auto-block reads. KARR_ROLE keeps those apart, and this
64 # keeps the instruction with the identity it belongs to.
65 #
66 # A caller that brings its OWN instruction passes it, and the coordination
67 # agent (#210) is the one that does: it is an agent and needs a prompt, but
68 # not the board's -- it is not there to work a card, and it is not even run
69 # in a board's own repository in the sense the drain means. `prompt => ...`
70 # is therefore the exception the two identities above make necessary, not a
71 # third way for a board agent to be told what to do.
72 local $ENV{PROMPT} = to_octets_for_env(
73 defined $opt{prompt} ? $opt{prompt}
74 : $role eq 'agent' ? $self->foundation->_prompt_for( $karr, $ticket )
75 : '' );
76  
77 # The id of the task this run is about, in ticket mode, and empty in every
78 # other mode -- localised either way so a run never inherits the previous
79 # one's card, and so a template reading it in drain mode gets nothing rather
80 # than a stale number. This is the whole machine-readable half of the ticket
81 # contract: the prompt above carries the assignment in prose for the agent,
82 # $KARR_TASK carries it for a command template that wants the bare id
83 # (`myagent --task "$KARR_TASK"`). Deliberately not an argument appended to
84 # the command -- how arguments are appended is what `kind: claude-code`
85 # settles per agent definition (#188), and an env var is the one thing that
86 # works with every command template that exists today, including the
87 # synthesized `claude -p "$PROMPT"`.
88 local $ENV{KARR_TASK} = defined $ticket ? to_octets_for_env("$ticket") : '';
89  
90 # The claim name this run holds its cards under, defaulted for every nested
91 # `karr` call the child makes (ADR 0005 / #281). `karr agent-name` and this
92 # have to produce the same string from the same checkout, so both go through
93 # App::karr::AgentName; the value is the checkout's own directory name (a
94 # claim visible in `karr show`, distinct per worktree). `unique => 1` appends
95 # a per-run random suffix -- foundation is the many-agent context, and two
96 # checkouts of one shared board could otherwise stamp the same bare name at
97 # once. It is minted ONCE here and exported, so it is the same value for
98 # every `karr` the child spawns during this run (stable per run, not per
99 # invocation -- which is why a fresh PID per call was rejected); a run that
100 # dies leaves at most this claim for claim_timeout to clear. Through the same
101 # %ENV octet edge KARR_TASK above uses, never a direct encode.
102 local $ENV{KARR_CLAIM} = to_octets_for_env( agent_name( dir => "$repo", unique => 1 ) );
103  
104 # The expansion is the shell's, not ours (#159). Splicing %ENV into the command
105 # string here instead meant the shell went on to parse the *values*: a prompt
106 # is board content written in Markdown, so its backtick spans and $(...) ran as
107 # commands in the board's own directory, and the substitution reached inside
108 # single quotes, where sh guarantees a literal — awk '{print $2}' arrived as
109 # awk '{print }'. Parameter expansion has neither problem: sh does not rescan
110 # an expanded value for substitutions, and it leaves single quotes alone. A
111 # template that needs a value the shell cannot see gets it exported above,
112 # never spliced.
113 #
114 # So this logs the template, which is now exactly the string /bin/sh -c is
115 # handed. It used to log the substituted result, which after this change is not
116 # even computable without reimplementing the shell — and what an operator reads
117 # this line for is which command was resolved (--command vs default_command vs
118 # .karr vs synthesized claude), not a second copy of the prompt. It also no
119 # longer copies whatever an env var held — a wrapper's API key included — into
120 # a plaintext .karr.log.
121 $self->foundation->_append_log( $repo, 'START '
122 . ( $role ne 'agent' ? "role=$role " : '' )
123 . ( ref $agent eq 'HASH' && defined $agent->{name} ? "agent=$agent->{name} " : '' )
124 . "command=$command" );
125 $self->foundation->_say_verbose("exec in $repo: $command");
126  
127 if ( $self->foundation->dry_run ) {
128 $self->foundation->_append_log( $repo, "DRY-RUN (skipped)" );
129 return ( 0, '' );
130 }
131  
132 my $log_file = $repo->child('.karr.log');
133  
134 # Opened before the command is started, not after (#147). Everything from the
135 # fork below to the waitpid at the end of this method runs with a live agent
136 # on the other side, and the drain loop that calls this catches per repo and
137 # moves on to the next board — so a croak in that window releases the board's
138 # lock with its agent still running and leaves one behind for the rest of the
139 # foundation run. Refusing to start an agent whose log cannot be written is
140 # the honest failure, and it is the one the foundation's own
141 # _append_log("START ...") above already makes for the same file.
142 # A resource the OS refused is the operator's problem, not a bug report, so
143 # this and the two below carry the errno and no call site into this file (#77).
144 open( my $log_fh, '>>', "$log_file" ) or user_error("open log $log_file: $!");
145 $log_fh->autoflush(1);
146  
147 # Native pipe: the child writes stdout+stderr, the parent reads. The parent
148 # is the tee — it fans each chunk to the persistent log, the terminal (when
149 # streaming), and an in-memory buffer for error scanning. No external tee
150 # process to race, and the run's output is captured directly (no re-slurping
151 # the log via byte offsets).
152 pipe( my $reader, my $writer ) or user_error("pipe failed: $!");
153  
154 my $pid = fork;
155 user_error("fork failed: $!") unless defined $pid;
156  
157 if ( $pid == 0 ) {
158 # child
159 close $reader;
160 chdir "$repo" or die "chdir $repo: $!";
161 open( STDOUT, '>&', $writer ) or die "dup stdout: $!";
162 open( STDERR, '>&STDOUT' ) or die "dup stderr: $!";
163 # The agent becomes its own process group leader so the runner can signal
164 # the whole tree (the agent, its forked grandchildren, anything it
165 # backgrounded) without reaching the runner itself (#148). Before this the
166 # timeout SIGTERM hit only the shell — `sleep 300 & wait`, a pipeline, any
167 # command the agent backgrounded, all survived the kill because they were
168 # children of /bin/sh, not of the runner. setpgrp(0,0) puts the child in a
169 # group whose pgid is its own pid; the parent signals that group with
170 # kill 'TERM', -$pid. SIGALRM is also reset to default in the child — the
171 # timeout timer is the runner's, not the agent's.
172 setpgid( 0, 0 ) if defined &setpgid;
173 POSIX::setsid() if !defined &setpgid; # fall back if POSIX::setpgid isn't there
174 $SIG{ALRM} = 'DEFAULT';
175 exec( '/bin/sh', '-c', $command ) or die "exec: $!";
176 }
177  
178 # parent. From here to the waitpid below there is a running agent, so nothing
179 # in between may die: no croaking call, and no unguarded call into the
180 # foundation (its _append_log throws when the log file is gone). Keep it that
181 # way — the tee loop below reports its errors by ending, not by dying.
182 close $writer;
183  
184 # setpgid in the child may race with the parent's getpgid (the child has not
185 # called it yet when fork returns in the parent). setpgid( $pid, $pid ) in the
186 # parent is idempotent if the child has already done it, and is the
187 # documented way to guarantee the value is set before we signal the group.
188 setpgid( $pid, $pid ) if defined &setpgid;
189  
190 # The runner is the only place that knows the agent's pid and pgid — the
191 # Foundation needs both so its SIGTERM handler can kill the agent's process
192 # group when the cron host stops us mid-drain (#163). Record them here, in
193 # the foundation's own attribute, so a handler installed in run() can reach
194 # them without re-reading the lock file (which it does anyway, defensively).
195 $self->foundation->_live_agent(
196 { repo => $repo, pid => $pid, pgid => $pid, lockfile => $self->foundation->_state->_lock_file( $repo ) }
197 );
198  
199 my $started = time;
200 my $output = '';
201 my $timed_out = 0;
202 my $sel = IO::Select->new($reader);
203  
204 # Deadline arming: the deadline must fire regardless of IO activity, because
205 # an agent that closes its stdout/stderr while still running ends the read
206 # loop on EOF with $timed_out still 0, and the runner falls into a bare
207 # blocking waitpid that holds .karr.lock forever (#161). SIGALRM with a
208 # handler that sets $timed_out keeps the deadline independent of the read
209 # loop: the alarm fires at the deadline, the handler arms the flag, the
210 # next loop iteration sees it and ends the loop. arm_alarm() also re-arms on
211 # each can_read wakeup so a long-running command never gets a stale timer
212 # from a prior iteration — every iteration arms for "remaining from now",
213 # which is what the user expects max_runtime to mean.
214 my $alarm_target;
215 if ( $max_runtime > 0 ) {
216 $alarm_target = $started + $max_runtime;
217 $SIG{ALRM} = sub {
218 $timed_out = 1;
219 # Closing the read end of the pipe unblocks can_read with no data so
220 # the loop wakes immediately rather than waiting for the alarm delivery
221 # to reach it through sysread's EINTR. Cheap and signal-safe.
222 close $reader;
223 $sel = undef;
224 };
225 alarm $max_runtime;
226 }
227  
228 # The agent's output arrives as raw octets in 64k reads that can split a
229 # multi-byte character, while STDOUT carries the :encoding(UTF-8) layer
230 # F<karr-foundation> installed and therefore wants characters. FB_QUIET is
231 # the streaming decoder: it consumes every complete sequence and leaves a
232 # trailing partial one in $pending for the next chunk. The log file and the
233 # error-scanning buffer keep the raw octets.
234 my $pending = '';
235  
236 # Line assembly for a rendered stream (see _render_stream_line). Only used
237 # when $render is on; the raw path below never touches them.
238 my $line_buf = '';
239 my $shown = '';
240  
241 while (1) {
242 last if $timed_out;
243 if ( !$sel ) {
244 # SIGALRM fired and closed $reader; nothing left to do but exit the loop
245 # so the kill path runs.
246 last;
247 }
248 my @ready = $sel->can_read( $max_runtime > 0 ? $max_runtime - ( time - $started ) : undef );
249 last if $timed_out;
250 unless (@ready) {
251 # Spurious wakeup (signal) or genuine deadline. SIGALRM would have set
252 # the flag, but the deadline could also be reached by wall clock if a
253 # signal reset the alarm — check both and end the loop either way.
254 next unless $max_runtime > 0;
255 last if time - $started >= $max_runtime;
256 next;
257 }
258 my $chunk;
259 my $n = sysread( $reader, $chunk, 65536 );
260 last if !defined $n; # read error (or SIGALRM closing the fd)
261 last if $n == 0; # EOF — the command closed its output
262 if ($render) {
263 $pending .= $chunk;
264 $line_buf .= Encode::decode( 'UTF-8', $pending, Encode::FB_QUIET );
265 while ( $line_buf =~ s/\A([^\n]*)\n// ) {
266 my $text = $self->_render_stream_line( $render, $1 );
267 next unless length $text;
268 print {$log_fh} to_octets($text);
269 print $text if $stream_terms;
270 $shown = substr $text, -1;
271 }
272 }
273 else {
274 print {$log_fh} $chunk;
275 if ($stream_terms) {
276 $pending .= $chunk;
277 print Encode::decode( 'UTF-8', $pending, Encode::FB_QUIET );
278 }
279 }
280 # The classification buffer keeps the raw octets whatever the terminal and
281 # the log were given: _run_result reads the result object out of the tail
282 # of the stream, and rendering has just dropped it on the floor.
283 $output .= $chunk;
284 }
285  
286 # A last line the command left without a newline (it was killed, or it simply
287 # does not end its output with one) still has something to say.
288 if ( $render && length $line_buf ) {
289 my $text = $self->_render_stream_line( $render, $line_buf );
290 if ( length $text ) {
291 print {$log_fh} to_octets($text);
292 print $text if $stream_terms;
293 $shown = substr $text, -1;
294 }
295 }
296 # Rendered text arrives as deltas and the last one rarely ends a line, so
297 # without this the shell prompt (and the next log line) lands mid-sentence.
298 if ( $render && length $shown && $shown ne "\n" ) {
299 print {$log_fh} "\n";
300 print "\n" if $stream_terms;
301 }
302  
303 # Disarm the alarm before reap: a waitpid that takes longer than max_runtime
304 # would otherwise be cut short by SIGALRM (no handler anymore — the default
305 # action is to die, and Foundation is the parent). $max_runtime == 0 already
306 # never armed.
307 alarm 0;
308 $SIG{ALRM} = 'DEFAULT' if $max_runtime > 0;
309  
310 my $exit_code;
311 if ($timed_out) {
312 my $elapsed = time - $started;
313 # The one call that has to happen here rather than after the kill: it is the
314 # only record of why the agent was stopped, and the kill/waitpid pair below
315 # can block for as long as the child stays unkillable. So it runs
316 # best-effort — a log the OS took away mid-run (#147) must not cost us the
317 # SIGTERM/SIGKILL and the reap, which are all that stop a hung agent. The
318 # failure is reported once the child is safely gone, and the END line below
319 # raises it for real if the log is still unwritable by then.
320 my $log_err;
321 eval {
322 $self->foundation->_append_log( $repo,
323 "TIMEOUT after ${elapsed}s -- sending SIGTERM to $pid (group -$pid)" );
324 1;
325 } or $log_err = clean_error($@);
326 # Negative pid = process group (kill(2) group semantics, #148). The shell,
327 # the agent, any grandchildren the agent backgrounded, all receive the
328 # signal. SIGTERM is catchable, so we wait up to 2s before escalating.
329 kill 'TERM', -$pid;
330 my $deadline = time + 2;
331 while ( time < $deadline ) {
332 last if kill( 0, $pid ) == 0;
333 select undef, undef, undef, 0.05;
334 }
335 kill 'KILL', -$pid;
336 waitpid( $pid, 0 );
337 warn "karr-foundation: cannot write $log_file: $log_err\n" if $log_err;
338 # 128 + SIGTERM(15) = 143 — same convention as shells, distinct from a
339 # clean non-zero exit, and surfaces in cooldown/last_error so an agent
340 # that exceeded max_runtime triggers the backoff (#164 / #161).
341 $exit_code = 128 + SIGTERM;
342 } else {
343 # The child may still be alive after the loop ended on EOF — a command
344 # whose stdout is closed while it keeps running (the classic
345 # `exec >/dev/null 2>&1; sleep N`, #161). Reap it with a wait loop that
346 # checks the wall-clock deadline: if the loop ended on EOF before
347 # max_runtime expired, this blocks until the child exits on its own or
348 # until the deadline arrives and we kill it via the timed_out path. The
349 # loop uses WNOHANG to keep checking; the deadline path is identical to
350 # the SIGALRM path above.
351 my $deadline;
352 if ( $max_runtime > 0 ) {
353 $deadline = $started + $max_runtime;
354 while (1) {
355 my $w = waitpid( $pid, WNOHANG );
356 last if $w > 0 || $w < 0;
357 if ( time >= $deadline ) {
358 $timed_out = 1;
359 kill 'TERM', -$pid;
360 my $term_deadline = time + 2;
361 while ( time < $term_deadline ) {
362 last if kill( 0, $pid ) == 0;
363 select undef, undef, undef, 0.05;
364 }
365 kill 'KILL', -$pid;
366 waitpid( $pid, 0 );
367 last;
368 }
369 select undef, undef, undef, 0.05;
370 }
371 } else {
372 waitpid( $pid, 0 );
373 }
374 $exit_code = _classify_exit($?);
375 $exit_code = 128 + SIGTERM if $timed_out && $exit_code == 0;
376 }
377  
378 close $reader if defined fileno $reader;
379 close $log_fh;
380  
381 # Clear the live-agent handle: the SIGTERM handler must not see this agent
382 # after we have reaped it. The next iteration of the drain (or the next
383 # repo) installs its own.
384 $self->foundation->_live_agent( undef );
385  
386 my $elapsed = time - $started;
387 $self->foundation->_append_log( $repo, "END elapsed=${elapsed}s exit=$exit_code" );
388 return ( $exit_code, $output );
389 }
390  
391 # Translate the raw $? from waitpid(2) into the exit code the drain sees. A
392 # child that exited normally: the high 8 bits are the status. A child that
393 # died from a signal: the low 7 bits are the signal number and the high 8
394 # bits are 0 — `$? >> 8` was 0 here, which is the bug #164 pins: the runner
395 # reported the OOM-killed / SIGTERM'd / SIGSEGV'd agent as exit 0, the drain
396 # read it as a clean run, and the cooldown that was supposed to catch a
397 # machine-killing agent never engaged. Surface the signal as 128 + signum so
398 # it is distinguishable from any real exit code (shells do the same), and
399 # fall through to the normal high-bits path otherwise.
400 #
401 # Accept both forms: the runner calls this as a function
402 # (`_classify_exit($?)`) and tests call it as a method (`$r->_classify_exit($?)`).
403 # `use Moo;` turns every sub in the package into a method, so the method
404 # form has $self as the first arg; the function form has $status as the first
405 # arg. Inspect $_[0]: if it's a blessed reference, it's $self and we look at
406 # $_[1] for $status.
407 sub _classify_exit {
408 my $status = ( ref $_[0] ) ? $_[1] : $_[0];
409 return 0 unless defined $status;
410 my $sig = $status & 127;
411 return 128 + $sig if $sig;
412 return ( $status >> 8 ) & 255;
413 }
414  
415 # ---------------------------------------------------------------------------
416 # Live output for a structured stream
417 # ---------------------------------------------------------------------------
418  
419 # One line of a rendered stream, as text for the terminal and the log, or the
420 # empty string for a line that carries nothing a human wants to read.
421 #
422 # This exists because of a trap in the `kind: claude-code` contract. A run has
423 # to be asked for structured output before it will report on itself, and plain
424 # `--output-format json` buys that by printing NOTHING until the run ends --
425 # which silently cancels the live output App::karr::Foundation promises for a
426 # TTY, on exactly the runs that take half an hour. `stream-json` ends with the
427 # same result object and streams on the way there, so the contract asks for
428 # that instead and the rendering happens here.
429 #
430 # What is rendered is the assistant's own text, which is the same choice
431 # App::karr::Foundation's documented jq pipeline makes
432 # (`select(.type == "stream_event") | .event.delta.text`). Everything else in
433 # the stream -- the init banner, the per-message envelopes, the tool plumbing,
434 # the final result object -- is machinery, and the machinery is what an
435 # operator watching a board does not want to read. The result object is not
436 # lost by suppressing it: the drain classifies from it (it stays in the raw
437 # buffer) and logs a RESULT line of its own.
438 #
439 # A line that is not JSON at all passes through verbatim. The pipe is shared
440 # with the command's stderr, so a wrapper's banner, a `set -x` trace or a
441 # warning can land between two stream events, and swallowing those would be
442 # the same mistake one level down.
443 sub _render_stream_line {
444 my ( $self, $render, $line ) = @_;
445 return '' unless $render eq 'stream-json';
446 return '' unless defined $line && $line =~ /\S/;
447 # Same cheap pre-filter as _run_result: prose never reaches the parser.
448 return "$line\n" unless $line =~ /\A\s*\{.*\}\s*\z/s;
449 my $ev = eval { json_decode($line) };
450 return "$line\n" unless ref $ev eq 'HASH';
451 return '' unless ( $ev->{type} // '' ) eq 'stream_event';
452 my $delta = ( $ev->{event} // {} )->{delta};
453 return '' unless ref $delta eq 'HASH';
454 my $text = $delta->{text};
455 return defined $text && !ref $text ? $text : '';
456 }
457  
458 # ---------------------------------------------------------------------------
459 # Structured result (a claude-code run's own report)
460 # ---------------------------------------------------------------------------
461  
462 # How much of a transcript is looked at for the report at its end. The buffer
463 # is everything the agent printed and can be megabytes; the object itself is a
464 # couple of kilobytes. A report that does not fit in the window fails to parse
465 # and the run counts as unstructured, which is the safe direction.
466 my $RESULT_TAIL_BYTES = 1_048_576;
467  
468 # The run's own report, or undef when it made none.
469 #
470 # How foundation finds out that a run answers structurally: it does not ask,
471 # and it is not told. It reads what the run left at the end of its output.
472 #
473 # The two alternatives are both worse. A configuration key ("this board's agent
474 # emits json") is a second copy of a fact the command already carries, and a
475 # copy that has gone stale is worse than no copy at all -- it makes foundation
476 # look for a report that is not there, or ignore one that is, and it puts the
477 # operator in charge of keeping two strings in step. Sniffing the command
478 # string for --output-format json means parsing a shell template foundation
479 # deliberately does not parse (#159: the expansion is the shell's, not ours),
480 # and it guesses wrong on the very pipeline this module's own documentation
481 # recommends -- `... --output-format stream-json ... | jq -r ...` carries the
482 # flag and delivers no JSON at all.
483 #
484 # What is not a guess is the output. `claude -p --output-format json` ends with
485 # exactly one line, a JSON object with "type":"result". That is the format's
486 # contract, so reading the tail asks the run itself.
487 #
488 # Only the LAST non-empty line is examined, and that is the whole answer to
489 # "an agent that mixes prose and JSON must not be misclassified":
490 #
491 # * prose BEFORE the object is irrelevant -- a wrapper's banner, a `set -x`
492 # line, a warning that reached the shared stdout/stderr pipe earlier;
493 # * prose CONTAINING an object cannot reach the classifier. An agent working
494 # a karr board prints the board, and a board can hold a pasted result
495 # object the way #160's board held a "503" and a "403". Anything that
496 # scans a whole transcript eventually reads the agent's own quotation as
497 # the agent's own report; a tail read cannot;
498 # * anything printed AFTER the object makes the run unstructured again and
499 # the text scan takes over. Structure is lost, never invented.
500 sub _run_result {
501 my ( $self, $output ) = @_;
502 return undef unless defined $output && length $output;
503 my $tail = length($output) > $RESULT_TAIL_BYTES
504 ? substr( $output, -$RESULT_TAIL_BYTES )
505 : $output;
506 my ( $last ) = grep { /\S/ } reverse split /\n/, $tail, -1;
507 return undef unless defined $last;
508 $last =~ s/\A\s+//;
509 $last =~ s/\s+\z//;
510 # Cheap pre-filter before the parser, the same bargain _match_error makes
511 # with its trigger substrings: nearly every run ends in prose, and prose is
512 # rejected here without JSON::MaybeXS ever seeing it.
513 return undef unless $last =~ /\A\{.*\}\z/s;
514 # The buffer holds octets (the tee keeps the log and the scan byte-exact),
515 # and json_decode is the character-level door -- App::karr::Encoding owns
516 # both crossings, so the decode is from_octets and nothing else.
517 my $data = eval { json_decode( from_octets( $last ) ) };
518 return undef unless ref $data eq 'HASH';
519 return undef unless ( $data->{type} // '' ) eq 'result';
520 return $data;
521 }
522  
523 # What the report says about how the run ended, as ( $error, $ended ):
524 #
525 # $ended always describes the ending, for the log and for .karr.state
526 # $error is set only where that ending is a common error -- the same
527 # currency _match_error returns, so the drain treats a reported
528 # error and a scanned one alike from there on
529 #
530 # A reported error is a hard signal, not a near-miss: it is the run's own
531 # statement about itself, not an inference drawn from its prose. The progress
532 # guard #160 put in front of the text scan therefore does not belong in front
533 # of this one -- that guard exists because a word search over a transcript
534 # cannot tell the agent's report from the board's contents, which is a problem
535 # a field in the agent's own result object does not have.
536 sub _result_error {
537 my ( $self, $result ) = @_;
538 return ( undef, 'success' ) unless $result->{is_error};
539  
540 my $subtype = $result->{subtype} // 'error';
541  
542 # A status from the provider is exactly the case the text scan was written
543 # for, arriving as a number in a field instead of a word in a sentence. The
544 # board backs off, as it always did for a rate limit.
545 my $api = $result->{api_error_status};
546 return ( "api $api", "api $api" ) if defined $api && length $api;
547  
548 # The turn budget ran out. This is the one error flag that reports no
549 # failure of the agent and none of the provider: both worked, the task was
550 # larger than the budget it was given, and the honest response is to run
551 # again rather than to park the board for an exponentially growing hour.
552 # So it names the ending and returns no error, and the run is judged the way
553 # every other run is -- by what the board did.
554 return ( undef, 'max turns' )
555 if $subtype eq 'error_max_turns'
556 || ( $result->{terminal_reason} // '' ) eq 'max_turns';
557  
558 return ( $subtype, $subtype );
559 }
560  
561 # The numbers worth keeping out of a report: how far the run got and what it
562 # cost. .karr.state carries the last one so an operator -- and the coordination
563 # agent this is groundwork for -- can read the last run's report without
564 # parsing .karr.log.
565 sub _result_summary {
566 my ( $self, $result, $ended ) = @_;
567 return {
568 ended => $ended,
569 turns => $result->{num_turns},
570 duration => $result->{duration_ms},
571 cost_usd => $result->{total_cost_usd},
572 session => $result->{session_id},
573 };
574 }
575  
576 # The same report as one .karr.log line. Every field is optional: a report is
577 # read for its is_error flag first of all, and one that carries no numbers is
578 # still a report.
579 sub _result_line {
580 my ( $self, $result, $ended ) = @_;
581 my @bits;
582 my ( $turns, $ms, $cost ) =
583 @{$result}{qw( num_turns duration_ms total_cost_usd )};
584 # looks_like_number, not a regex: these come out of somebody else's JSON and
585 # the only thing being asked is whether they can be printed as numbers. A
586 # field that cannot is left out of the line rather than warned about -- a
587 # report is read for its error flag first of all, and one carrying no usable
588 # numbers is still a report.
589 push @bits, ( $turns == 1 ? '1 turn' : "$turns turns" )
590 if looks_like_number( $turns );
591 push @bits, sprintf( '%.1fs', $ms / 1000 ) if looks_like_number( $ms );
592 push @bits, sprintf( '$%.4f', $cost ) if looks_like_number( $cost );
593 return "RESULT $ended" . ( @bits ? ' (' . join( ', ', @bits ) . ')' : '' );
594 }
595  
596 # ---------------------------------------------------------------------------
597 # Common-error detection
598 # ---------------------------------------------------------------------------
599  
600 # What the drain scans an agent's transcript for: a failure the agent reports
601 # while still exiting 0 -- a rate limit, a dead key, a 5xx -- because that run
602 # produced nothing and starting the next one immediately just spends the next
603 # window on the same wall.
604 #
605 # These were bare case-insensitive substrings (network, quota, credentials,
606 # 401, 403, 429, 503, ...) matched against the whole transcript. That is not a
607 # near-miss instrument, it is a word search over everything the agent printed,
608 # and an agent working a karr board prints the board: a backlog line reading
609 # "retry the network fetch on 503" tripped it twice over, and "403" tripped on
610 # a diffstat (#160). So a symptom word on its own never counts here. It counts
611 # next to a failure word on the same line ($SIGNAL / _near), or inside one of
612 # the fixed phrases an API really emits. Numbers are the worse half -- 403 is a
613 # line count, a byte count, a task id -- so an HTTP status counts only where
614 # something adjacent says it is one (_http).
615 #
616 # Every quantifier below is bounded and every gap stays inside one line: this
617 # runs over megabytes of agent output, and an unbounded gap between two classes
618 # that share characters backtracks quadratically over a banner rule.
619  
620 # A word that turns a symptom into a report of failure. Deliberately excludes
621 # "retry", "limit" and "timeout" on their own: those are what a backlog full of
622 # networking tickets says, not what a failing API says.
623 my $SIGNAL = qr/\b(?:
624 error | errors | failed | failing | failure | refused | rejected | denied
625 | unavailable | unreachable | invalid | missing | expired | revoked | unable
626 | exceeded | exhausted
627 )\b/xi;
628  
629 # Limits are reported with verbs of their own.
630 my $LIMIT = qr/\b(?:
631 exceed(?:ed|s|ing)? | reach(?:ed|ing)? | hit | hitting | exhausted
632 | throttl(?:ed|ing) | error | over
633 )\b/xi;
634  
635 # $symptom counts only within one line of a failure word, in either order.
636 sub _near {
637 my ( $symptom, $signal ) = @_;
638 $signal //= $SIGNAL;
639 return qr/ (?: $symptom [^\n]{0,40}? $signal ) | (?: $signal [^\n]{0,40}? $symptom ) /x;
640 }
641  
642 # An HTTP status, only where something adjacent marks it as one: an
643 # http/status/code/error token just before it -- with nothing but punctuation,
644 # a "code"/"status" word or a protocol version in between -- or its own reason
645 # phrase directly after it. " | 403 ++++++" and "line 403" mark neither.
646 my $GAP = qr/[ \t:=,.\-\/\(\[]{0,8}/;
647  
648 sub _http {
649 my ( $code, $phrase ) = @_;
650 return qr/
651 (?: \b (?: https? | status | code | error | err | response ) \b
652 $GAP (?: code | status | \d+\.\d+ )? $GAP \b $code \b )
653 | (?: \b $code \b [ \t:,\-\(\[]{0,4} $phrase )
654 /xi;
655 }
656  
657 # [ name => regex ]. The name is what reaches .karr.log and .karr.state, and it
658 # keeps the wording of the substring it replaces so an operator's grep for
659 # "COMMON-ERROR rate limit" still finds it.
660 # Middle field: lowercase literals the pattern cannot match without. It is a
661 # pre-filter, not a pattern (see _match_error) -- these regexes are 30x the
662 # work of the substrings they replace, and a transcript is megabytes.
663 my @DEFAULT_PATTERNS = (
664 # rate limiting / capacity
665 [ 'rate limit', ['rate'],
666 _near( qr/\brate[_ -]?limit(?:s|ed|ing)?\b/i, $LIMIT ) ],
667 [ 'rate limit', ['rate_limit_error'], qr/\brate_limit_error\b/i ],
668 [ 'usage limit', ['usage limit'], _near( qr/\busage limit\b/i, $LIMIT ) ],
669 [ 'quota', ['quota'], _near( qr/\bquotas?\b/i, $LIMIT ) ],
670 [ 'overloaded', ['overloaded_error'], qr/\boverloaded_error\b/i ],
671 [ 'overloaded', ['overload','overcapacity'],
672 _near( qr/\bover(?:loaded|capacity)\b/i ) ],
673 [ 'too many requests', ['too many requests'], qr/\btoo many requests\b/i ],
674 [ '429', ['429'], _http( 429, qr/too many requests/i ) ],
675 [ '529', ['529'], _http( 529, qr/overloaded/i ) ],
676 # authentication
677 [ 'invalid api key', ['api'],
678 qr/\b(?:invalid|missing|expired|revoked|no)\s+api[_ -]?key\b
679 | \bapi[_ -]?key\b [^\n]{0,24}?
680 \b(?:invalid|missing|expired|revoked|required|not\s+found)\b/xi ],
681 [ 'authentication', ['authentication_error'], qr/\bauthentication_error\b/i ],
682 [ 'authentication', ['authenticat'], _near( qr/\bauthenticat(?:ion|ed|e)\b/i ) ],
683 [ 'credentials', ['credential'], _near( qr/\bcredentials?\b/i ) ],
684 [ 'unauthorized', ['unauthori'], _near( qr/\bunauthori[sz]ed\b/i ) ],
685 [ 'forbidden', ['forbidden'], _near( qr/\bforbidden\b/i ) ],
686 [ '401', ['401'], _http( 401, qr/unauthori[sz]ed/i ) ],
687 [ '403', ['403'], _http( 403, qr/forbidden/i ) ],
688 # network / transport
689 [ 'network', ['network'], _near( qr/\bnetwork\b/i ) ],
690 [ 'connection', ['connection'],
691 qr/\bconnection\s+(?:refused|reset|closed|aborted|error|failed)\b/i ],
692 [ 'connection',
693 [qw( econnrefused econnreset etimedout ehostunreach enetunreach enotfound eai_again )],
694 qr/\bE(?:CONNREFUSED|CONNRESET|TIMEDOUT|HOSTUNREACH|NETUNREACH|NOTFOUND|AI_AGAIN)\b/i ],
695 [ 'fetch failed', ['fetch failed'], qr/\bfetch failed\b/i ],
696 # /x eats a literal space, so every phrase here spells it \s+.
697 [ 'name resolution', ['resolve host','name resolution','service not known'],
698 qr/\bcould\s+not\s+resolve\s+host\b
699 | \btemporary\s+failure\s+in\s+name\s+resolution\b
700 | \bname\s+or\s+service\s+not\s+known\b/xi ],
701 [ 'timed out', ['time'],
702 qr/\b(?:connection|connect|request|socket|read|write|handshake|operation|upstream)\b
703 [^\n]{0,16}? \btimed?[ _-]?out\b/xi ],
704 # server side
705 [ 'service unavailable', ['service unavailable'], qr/\bservice unavailable\b/i ],
706 [ 'internal server error', ['internal server error'], qr/\binternal server error\b/i ],
707 [ 'bad gateway', ['bad gateway'], qr/\bbad gateway\b/i ],
708 [ '500', ['500'], _http( 500, qr/internal server error/i ) ],
709 [ '502', ['502'], _http( 502, qr/bad gateway/i ) ],
710 [ '503', ['503'], _http( 503, qr/service unavailable/i ) ],
711 );
712  
713 sub _error_patterns {
714 my ( $self, $karr ) = @_;
715 # A board's own error_patterns stay what they were documented as: plain
716 # case-insensitive substrings. Somebody who configures one has seen the
717 # string their agent prints and means exactly it -- the narrowing above is
718 # for the defaults, which have to hold for every board. Such a pattern is
719 # its own pre-filter.
720 my @custom = map { [ $_, [ lc $_ ], qr/\Q$_\E/i ] }
721 @{ $karr->{error_patterns} // [] };
722 return [ @DEFAULT_PATTERNS, @custom ];
723 }
724  
725 sub _match_error {
726 my ( $self, $text, $patterns ) = @_;
727 return undef unless defined $text && length $text;
728 # The pre-filter earns its keep on the output that has none of this in it,
729 # which is nearly all of it: index() over a whole transcript is a memory
730 # scan, these patterns are not, and skipping one that cannot match costs a
731 # single index instead of a full pass. A trigger that does not occur in what
732 # its own pattern matches would silently switch that pattern off, so t/152
733 # checks the two against each other over the corpus.
734 my $lc;
735 for my $p ( @$patterns ) {
736 my ( $name, $triggers, $re ) =
737 ref $p eq 'ARRAY' ? @$p : ( $p, [ lc $p ], qr/\Q$p\E/i );
738 $lc //= lc $text;
739 next unless grep { index( $lc, $_ ) >= 0 } @$triggers;
740 return $name if $text =~ $re;
741 }
742 return undef;
743 }
744  
745 1;
746  
747 __END__
« blib/lib/App/karr/Cmd/Unlock.pm ↑ Summary blib/lib/App/karr/Cmd/Delete.pm »