blib/lib/App/karr/Foundation/Coordinator.pm untested

filter: Statementstmt 0.0% 0 / 201 Branchbran 0.0% 0 / 90 Conditioncond 0.0% 0 / 42 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 397 CC 46 SCAR 35.9
CC
46
Cov
0%
route
90.0
_build_assignment
56.0
want
56.0
CRAP 36.2
1 # ABSTRACT: karr-foundation's judgement layer -- the coordination agent, called only on deviation
2  
3 package App::karr::Foundation::Coordinator;
4 our $VERSION = '0.602';
5 use Moo;
6 use POSIX qw( strftime );
7 use Path::Tiny;
8 use Try::Tiny;
9 use App::karr::Error qw( user_error clean_error );
10 use App::karr::Encoding qw( yaml_load );
11  
12  
13  
14 has foundation => (
15 is => 'ro',
16 weak_ref => 1,
17 required => 1,
18 );
19  
20 # The literal an assignment chain uses for "rather wait than take anything
21 # below this line". Matched case-insensitively: it is written by a language
22 # model, and refusing `wait` because it is not `WAIT` would park a board over
23 # a shift key.
24 my $WAIT = 'wait';
25  
26 sub _stamp {
27 my ( $epoch ) = @_;
28 return '?' unless defined $epoch && "$epoch" =~ /\A[0-9]+\z/;
29 return strftime( '%Y-%m-%dT%H:%M:%SZ', gmtime($epoch) );
30 }
31  
32 # ---------------------------------------------------------------------------
33 # Which agent
34 # ---------------------------------------------------------------------------
35  
36  
37 has name => (
38 is => 'lazy',
39 builder => '_build_name',
40 );
41  
42 sub _build_name {
43 my ( $self ) = @_;
44 my $defs = $self->foundation->_agents->definitions;
45 my @named = grep { ( $defs->{$_}{role} // '' ) eq 'coordinator' } sort keys %$defs;
46 return undef unless @named;
47 user_error( 'Agents ' . join( ' and ', @named )
48 . " are both marked 'role: coordinator'; exactly one agent can be the "
49 . 'fleet\'s judgement layer' ) if @named > 1;
50 return $named[0];
51 }
52  
53  
54 sub configured { return defined $_[0]->name }
55  
56 # ---------------------------------------------------------------------------
57 # The assignment
58 # ---------------------------------------------------------------------------
59  
60  
61 has assignment_file => (
62 is => 'lazy',
63 builder => '_build_assignment_file',
64 );
65  
66 sub _build_assignment_file {
67 my ( $self ) = @_;
68 return $self->foundation->_config_path->sibling('assignment.yml');
69 }
70  
71  
72 has assignment => (
73 is => 'lazy',
74 builder => '_build_assignment',
75 );
76  
77 sub _build_assignment {
78 my ( $self ) = @_;
79 my $file = $self->assignment_file;
80 return { repos => {} } unless $file->exists;
81  
82 my $data = try {
83 # slurp_utf8 gives characters and yaml_load takes them: the two halves of
84 # the one crossing App::karr::Encoding owns.
85 yaml_load( $file->slurp_utf8 );
86 } catch {
87 warn "karr-foundation: cannot read $file: " . clean_error($_) . "\n";
88 undef;
89 };
90 return { repos => {}, broken => "the assignment in $file could not be read" }
91 unless ref $data eq 'HASH';
92  
93 my $repos = $data->{repos};
94 return { repos => {}, broken => "the assignment in $file has no 'repos:' mapping" }
95 unless ref $repos eq 'HASH';
96  
97 my %by_path;
98 for my $key ( keys %$repos ) {
99 my $chain = $repos->{$key};
100 # A one-element list written as a scalar is what YAML invites and what the
101 # chain's own `needs` already accepts; refusing it here would be pedantry.
102 $chain = [ $chain ] if defined $chain && !ref $chain;
103 next unless ref $chain eq 'ARRAY';
104 my @names = grep { defined && length } map { ref $_ ? undef : $_ } @$chain;
105 $by_path{ _key( $key ) } = \@names;
106 }
107 return { repos => \%by_path };
108 }
109  
110 # One spelling for a repository path, so a board discovered through `scan:` and
111 # the same board written into the assignment by hand match. realpath needs the
112 # path to exist; where it does not, the string is the best answer there is.
113 sub _key {
114 my ( $path ) = @_;
115 my $p = try { path("$path")->realpath } catch { undef };
116 return defined $p ? "$p" : "$path";
117 }
118  
119  
120 sub route {
121 my ( $self, $repo ) = @_;
122 my $assignment = $self->assignment;
123  
124 if ( defined( my $broken = $assignment->{broken} ) ) {
125 $self->want( reason => $broken );
126 return undef;
127 }
128  
129 my $chain = $assignment->{repos}{ _key($repo) };
130 unless ( $chain && @$chain ) {
131 $self->want( repo => "$repo",
132 reason => 'no assignment names this repository' );
133 return undef;
134 }
135  
136 my $agents = $self->foundation->_agents;
137 my @failing;
138 for my $entry ( @$chain ) {
139 return { wait => 'the assignment says WAIT for this board'
140 . ( @failing ? ' (after ' . join( ', ', @failing ) . ', which '
141 . ( @failing == 1 ? 'is' : 'are' ) . ' failing)' : '' ) }
142 if lc $entry eq $WAIT;
143  
144 # An agent this machine does not define is dropped with a note rather than
145 # refused, the way a chain header's per-agent limit is: agent definitions
146 # are local and only local, so a table written where more of them exist is
147 # a normal thing to meet, not a broken one.
148 unless ( $agents->definitions->{$entry} ) {
149 $self->foundation->_say_verbose(
150 "assignment: no agent '$entry' is defined here, trying the next" );
151 next;
152 }
153 return { agent => $entry } if $agents->available( $entry );
154 push @failing, $entry;
155 }
156  
157 return { wait => 'every agent the assignment names for this board is failing ('
158 . join( ', ', @failing ) . ')' } if @failing;
159  
160 $self->want( repo => "$repo",
161 reason => 'the assignment names no agent this machine has for this repository' );
162 return undef;
163 }
164  
165 # ---------------------------------------------------------------------------
166 # Wants
167 # ---------------------------------------------------------------------------
168  
169  
170 has wanted => (
171 is => 'ro',
172 default => sub { [] },
173 );
174  
175 # Which entries have already been recorded, so one tick that meets the same
176 # deviation twice -- _plan_repos and _process_repo both resolve every board --
177 # does not say it twice in the prompt.
178 has _seen => (
179 is => 'ro',
180 default => sub { {} },
181 );
182  
183  
184 sub want {
185 my ( $self, %what ) = @_;
186 return 0 unless $self->configured;
187 my $reason = $what{reason};
188 return 0 unless defined $reason && length $reason;
189 my $key = join "\0", map { defined $what{$_} ? $what{$_} : '' }
190 qw( step repo reason );
191 return 0 if $self->_seen->{$key}++;
192 push @{ $self->wanted }, {
193 reason => $reason,
194 ( defined $what{step} ? ( step => "$what{step}" ) : () ),
195 ( defined $what{repo} ? ( repo => "$what{repo}" ) : () ),
196 };
197 return 1;
198 }
199  
200 # One deviation as the prompt says it: what it is about, then what it was.
201 sub _line {
202 my ( $want ) = @_;
203 my $what = defined $want->{step} ? "step $want->{step}"
204 : defined $want->{repo} ? $want->{repo}
205 : undef;
206 return defined $what ? "$what: $want->{reason}" : $want->{reason};
207 }
208  
209 # ---------------------------------------------------------------------------
210 # The call
211 # ---------------------------------------------------------------------------
212  
213  
214 sub dispatch {
215 my ( $self ) = @_;
216 my @wanted = @{ $self->wanted };
217 return 0 unless @wanted;
218  
219 # Emptied first: whatever happens below, this tick has had its one call, and
220 # a second dispatch must not turn one deviation into two runs.
221 @{ $self->wanted } = ();
222  
223 my $f = $self->foundation;
224 my $name = $self->name or return 0;
225 my $why = join '; ', map { _line($_) } @wanted;
226  
227 if ( $f->dry_run ) {
228 print "would call the coordination agent '$name' for "
229 . scalar(@wanted) . " deviation(s): $why\n";
230 return 0;
231 }
232  
233 my $git = $f->_hub_git;
234 unless ( $git ) {
235 warn "karr-foundation: the coordination agent '$name' is wanted ($why) but "
236 . "this machine has no hub -- name one with 'hub: /path/to/repo' in "
237 . $f->_config_path . "\n";
238 return 0;
239 }
240 my $hub = $git->dir;
241  
242 # An agent like any other, including this: while it is failing, it is not
243 # run. The place that wanted it waits, which is the behaviour F<karr-foundation>
244 # had before there was a coordination agent at all, and the wait ends by
245 # itself when probe_every comes round.
246 unless ( $f->_agents->available( $name ) ) {
247 my $av = $f->_agents->availability( $name );
248 my $wait = ( $av->{next_attempt} // 0 ) - time;
249 print "the coordination agent '$name' is failing"
250 . ( defined $av->{last_error} ? " ($av->{last_error})" : '' )
251 . ", next attempt in ${wait}s -- the plan waits\n";
252 return 0;
253 }
254  
255 unless ( $f->_acquire_lock( $hub ) ) {
256 print "the coordination agent '$name' is wanted, but the hub $hub is busy "
257 . "-- the plan waits for the next tick\n";
258 return 0;
259 }
260  
261 print "calling the coordination agent '$name' for " . scalar(@wanted)
262 . " deviation(s): $why\n";
263 $f->_append_log( $hub, 'COORDINATION wanted: ' . $why );
264  
265 my $ran = try {
266 $self->_invoke( $hub, $name, \@wanted );
267 } catch {
268 warn "karr-foundation: the coordination agent failed to start: "
269 . clean_error($_) . "\n";
270 0;
271 };
272 $f->_release_lock( $hub );
273 return $ran;
274 }
275  
276 # The invocation itself, once the tick has decided it may happen: the agent's
277 # own command under its own contract (#188), the deviations as its prompt, and
278 # its own result object as the verdict (#187).
279 sub _invoke {
280 my ( $self, $hub, $name, $wanted ) = @_;
281 my $f = $self->foundation;
282 my $inv = $f->_agents->invocation( $name );
283  
284 my ( $exit, $output ) = $f->_run_command(
285 $hub, $f->_load_karr( $hub ), $inv->{command}, undef, $inv,
286 role => 'coordinator',
287 prompt => $self->prompt( $wanted ),
288 );
289  
290 my ( $err, $ended );
291 my $report = $f->_run_result( $output );
292 if ( $report ) {
293 ( $err, $ended ) = $f->_result_error( $report );
294 # The same reading the drain makes of an exit the report does not account
295 # for: the report is the agent's, the exit code may be a wrapper's.
296 $err //= "exit=$exit" if $exit != 0 && !$report->{is_error};
297 $f->_append_log( $hub, $f->_result_line( $report, $ended ) );
298 }
299 elsif ( $exit != 0 ) {
300 $err = "exit=$exit";
301 }
302  
303 if ( defined $err ) {
304 $f->_agents->record_failure( $name, $err );
305 $f->_append_log( $hub, "COORDINATION failed: $err" );
306 print "the coordination agent '$name' failed: $err\n";
307 return 0;
308 }
309  
310 $f->_agents->record_success( $name );
311 $f->_append_log( $hub, 'COORDINATION ' . ( $ended // 'done' ) );
312 print "the coordination agent '$name' finished ("
313 . ( $ended // 'no report' ) . "); the next tick runs what it wrote\n";
314 return 1;
315 }
316  
317 # ---------------------------------------------------------------------------
318 # The prompt
319 # ---------------------------------------------------------------------------
320  
321  
322 sub prompt {
323 my ( $self, $wanted ) = @_;
324 my $f = $self->foundation;
325 my $hub = $f->_hub_git ? $f->_hub_git->dir : '(none)';
326  
327 my @out;
328 push @out, <<'INTRO';
329 You are the coordination agent of this karr fleet -- its judgement layer.
330 karr-foundation works through written plans on its own and calls you only when
331 a plan is missing or has broken; between two of those calls no AI runs at all.
332 Everything you write is read back by machinery that runs without you, so write
333 it in the shapes below and in no other.
334 INTRO
335  
336 push @out, "WHY YOU WERE CALLED\n"
337 . join( '', map { ' - ' . _line($_) . "\n" } @$wanted );
338  
339 push @out, "WHERE THINGS ARE\n"
340 . sprintf( " fleet config %s\n", $f->_config_path )
341 . sprintf( " assignment %s\n", $self->assignment_file )
342 . sprintf( " availability %s (karr writes it; read it, never edit it)\n",
343 $f->_agents->state_file )
344 . sprintf( " hub repository %s (refs/karr-foundation/*: chain, run log, questions)\n", $hub )
345 . " Read a board with 'karr list --compact', 'karr board', 'karr show ID'\n"
346 . " in its repository, and the fleet with 'karr-foundation --status --verbose'.\n";
347  
348 push @out, $self->_agent_block;
349  
350 my $routing = $f->_config_data->{routing};
351 push @out, "HOW THE OPERATOR WANTS THEM USED\n"
352 . ( defined $routing && length $routing
353 ? _indent( $routing )
354 : " Nothing written. The operator can put prose in the config's "
355 . "'routing:' key.\n" );
356  
357 push @out, $self->_writes_block;
358  
359 push @out, <<'LIMITS';
360 WHAT YOU MUST NOT DO
361 - Name an agent in a chain step. The chain is shared with every machine in
362 the fleet and an agent exists on one machine and not on the next; routing
363 is the assignment's job and the assignment is local.
364 - Lift a block on a card. A cross-board link is a fact and 'blocked' is a
365 decision: 'karr needs --resolve' or a person makes it.
366 - Plan a card that sits in backlog, or move one out of it. Backlog is held
367 back on purpose; promoting a card to todo is the maintainer's call.
368 - Plan two agents into one repository at the same time. One agent per
369 repository is the fleet's one hard rule; concurrency is across
370 repositories.
371 - Teach karr anything domain-specific. What "done" means for a project, how
372 a release is verified and which project depends on which reach karr only
373 through a board's on_drained hook and through the prose above.
374 LIMITS
375  
376 return join "\n", @out;
377 }
378  
379 # The agents this machine has, with what is known about each right now. The
380 # description is printed as written: it is the selection criterion, and a
381 # language model reads prose better than it matches a taxonomy, so nothing
382 # here reformats or truncates it.
383 sub _agent_block {
384 my ( $self ) = @_;
385 my $agents = $self->foundation->_agents;
386 my $defs = $agents->definitions;
387 my @names = sort keys %$defs;
388 return "THE AGENTS ON THIS MACHINE\n None are defined.\n" unless @names;
389  
390 my $out = "THE AGENTS ON THIS MACHINE\n";
391 for my $name ( @names ) {
392 my $def = $defs->{$name};
393 $out .= sprintf " %s kind: %s %s%s\n", $name, $def->{kind},
394 $self->_availability( $name ),
395 ( ( $def->{role} // '' ) eq 'coordinator' ? ' [you]' : '' );
396 next unless defined $def->{description} && length $def->{description};
397 my $text = $def->{description};
398 $text =~ s/\s+\z//;
399 $out .= " $_\n" for split /\n/, $text;
400 }
401 return $out;
402 }
403  
404 sub _availability {
405 my ( $self, $name ) = @_;
406 my $av = $self->foundation->_agents->availability( $name );
407 return 'ok' unless ( $av->{state} // 'ok' ) eq 'failing';
408 return 'failing since ' . _stamp( $av->{failing_since} )
409 . ', next attempt at ' . _stamp( $av->{next_attempt} )
410 . ( defined $av->{last_error} ? " ($av->{last_error})" : '' );
411 }
412  
413 # The three things it may write, each with the exact shape karr reads back. Two
414 # of them are commands and are spelled out as commands: an agent that has to
415 # guess at an interface writes something nobody can execute. Until #213 the
416 # chain was the exception -- there was no command for it, so this block carried
417 # a perl -e one-liner against ChainStore, which made a storage API an agent's
418 # interface and left every rename in that class breaking a prompt instead of a
419 # call.
420 sub _writes_block {
421 my ( $self ) = @_;
422 my $file = $self->assignment_file;
423 my $karr = $self->_foundation_command;
424 return <<"WRITES";
425 WHAT YOU MAY WRITE
426  
427 1. THE ASSIGNMENT -- $file
428 Repository path to the ordered list of agents that may work that board.
429 karr-foundation takes the first entry that currently works, and WAIT means
430 "rather wait than use anything further down". Only the names above, plus
431 WAIT. Name every repository of the fleet: one that is missing calls you
432 again on the next tick, so a board nothing should run on gets a chain of
433 its own that is just WAIT.
434  
435 repos:
436 /path/to/repo:
437 - agent-name
438 - another-agent
439 - WAIT
440  
441 2. A CHAIN, in the hub. Keep it short: a long chain goes stale faster than it
442 is worked through. A step carries id, kind (ticket | shell | question |
443 plan), repo, ticket, needs (step ids -- the edges of the DAG), timeout,
444 precheck, command and note. A precheck is '<fact> == <value>' or '!=' over
445 board_actionable, ticket_status, ticket_blocked, ticket_claimed,
446 ticket_links and question_state; a step whose precheck no longer holds is
447 not executed -- it goes stale and calls you again. Write the whole chain as
448 one YAML (or JSON) document on stdin; it REPLACES the chain that is there,
449 so it is the plan as you now think it should be, not an addition to it:
450  
451 $karr plan <<'CHAIN'
452 steps:
453 - id: 1
454 kind: ticket
455 repo: /path/to/repo
456 ticket: 7
457 precheck: ticket_status == todo
458 - id: 2
459 kind: shell
460 repo: /path/to/repo
461 needs: [ 1 ]
462 command: ./gate.sh
463 limits:
464 concurrent: 2
465 note: what this plan is for
466 CHAIN
467  
468 Add --dry-run to have a chain checked and told back to you without writing
469 it. A chain that still has a step running is refused rather than replaced;
470 --force replaces it anyway, and is not what you want unless you know what
471 that step was doing.
472  
473 3. A QUESTION, always in advance and never from inside a step:
474  
475 $karr ask "which registry do we publish to?" \\
476 --context "the release gate is waiting" \\
477 --options cpan,darkpan --default cpan --policy use_default \\
478 --wait 3600 --step 2
479  
480 A kind: question step waits until every question naming it is settled.
481 WRITES
482 }
483  
484 # How this agent has to spell karr-foundation for it to find the fleet it was
485 # called for. Without --config the binary reads ~/.config/karr-foundation, and
486 # a fleet started with one somewhere else would have its plan written into a
487 # config that does not exist -- the agent would be told a command that cannot
488 # work and would have no way of knowing.
489 sub _foundation_command {
490 my ( $self ) = @_;
491 my $config = $self->foundation->config;
492 return 'karr-foundation' unless defined $config && length $config;
493 return "karr-foundation --config '$config'";
494 }
495  
496 sub _indent {
497 my ( $text ) = @_;
498 $text =~ s/\s+\z//;
499 return join '', map { " $_\n" } split /\n/, $text;
500 }
501  
502 1;
503  
504 __END__