blib/lib/App/karr/Foundation.pm

filter: Statementstmt 94.8% 37 / 39 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 13 / 13 Podpod n/a totaltotal 96.1% 50 / 52 CC 1 SCAR 0.2
CC
1
Cov
95%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/App/karr/Git.pm ↑ Summary blib/lib/App/karr/Role/CompactOutput.pm »
1 # ABSTRACT: Single-shot foundation daemon -- periodic agent execution across karr boards
2  
3 package App::karr::Foundation;
4 our $VERSION = '0.602';
5 9 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use MooX::Options (
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 usage_string => 'USAGE: karr-foundation [ask QUESTION | answer ID ANSWER | chain | plan] [options]',
8 # The mailbox commands (#191) are positional, and MooX::Options hands the
9 # leftovers back in @ARGV only when it is allowed to consume the options out
10 # of it. Nothing else in this class reads @ARGV, and F<bin/karr-foundation>
11 # passes what is left to run().
12 protect_argv => 0,
13 9 );
14 9 ▶use App::karr::Error qw( user_error clean_error );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 9 ▶use App::karr::Encoding qw( from_octets yaml_load );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 9 ▶use App::karr::Role::ExitCodes;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 9 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 9 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 9 ▶use POSIX qw( SIGTERM SIGINT SIGHUP WNOHANG );
Subroutine BEGIN: called CC=1 SCAR=0.0
20 9 ▶use YAML::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 9 ▶use Time::Piece;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 9 ▶use Digest::MD5 qw( md5_hex );
Subroutine BEGIN: called CC=1 SCAR=0.0
23 9 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 0 ▶use App::karr::Git;
Subroutine BEGIN: called CC=1 SCAR=2.6
25 use App::karr::BoardStore;
26 use App::karr::ActivityLog;
27 use App::karr::Foundation::Runner;
28 use App::karr::Foundation::State;
29 use App::karr::Foundation::Overview;
30 use App::karr::Foundation::Picker;
31 use App::karr::Foundation::Agents;
32 use App::karr::Foundation::ChainStore;
33 use App::karr::Foundation::Executor;
34 use App::karr::Foundation::Questions;
35 use App::karr::Foundation::Coordinator;
36 use App::karr::Foundation::Limits;
37  
38 # An unknown option or an option value that does not parse exits 2, not 1
39 # (ADR 0002 exit-code contract). MooX::Options otherwise hands that failure a
40 # 1, which is the code a genuine runtime failure of a drain carries, and the
41 # central handler in F<bin/karr-foundation> never sees those exits at all.
42 with 'App::karr::Role::ExitCodes';
43  
44 # An option name with a dash in it does not survive standing behind a boolean
45 # flag -- MooX::Options re-emits the token after a recognised option verbatim,
46 # so `karr-foundation --verbose --dry-run` reached Getopt::Long under a name
47 # the specification does not have (ticket #256). F<bin/karr> routes around it
48 # for every command class; this binary needs the same walk for the same
49 # reason, and `dry_run` -- the spelling the SYNOPSIS itself uses -- is the
50 # option it applies to here.
51 with 'App::karr::Role::CliArgs';
52  
53 # Instruction handed to a synthesized agent command via the $PROMPT variable
54 # when neither the .karr file nor the config overrides it.
55 #
56 # The backlog sentence is there because "the next actionable task" is the
57 # phrase an agent with an empty `karr pick` goes looking for work under, and a
58 # backlog card promoted by that agent is a hold that no longer holds (k306):
59 # moving a card out of backlog is the maintainer's call.
60 our $DEFAULT_PROMPT =
61 'Use the karr-coordinator skill: pick the next actionable task on this '
62 . 'board, complete it, and move it forward. If you cannot proceed, block '
63 . 'the task with a reason. Leave cards in backlog where they are: moving '
64 . 'one to todo is the maintainer\'s call.';
65  
66 # The same, for a ticket-mode run. It cannot be $DEFAULT_PROMPT: that one opens
67 # by telling the agent to pick its own work, which is the one thing a run that
68 # has already been given a card must not do.
69 our $DEFAULT_TICKET_PROMPT =
70 'Use the karr-coordinator skill: work on the one task named below, '
71 . 'complete it, and move it forward. If you cannot proceed, block the task '
72 . 'with a reason.';
73  
74 # Appended to whatever prompt was resolved, ticket id spliced in by foundation
75 # itself. It has to be foundation that splices: the prompt reaches the agent as
76 # $PROMPT and /bin/sh does not rescan an expanded value, so a prompt writing
77 # $KARR_TASK would hand the agent those ten characters (#159). Last, not first,
78 # because it has to win over an operator prompt that says "pick the next task".
79 our $TICKET_ASSIGNMENT =
80 'The task for this run is #%s: work on that one task and no other. Claim '
81 . 'it before you start, and stop when it is done, handed off or blocked. Do '
82 . 'not pick up another task.';
83  
84 option config => (
85 is => 'ro',
86 format => 's',
87 doc => 'Path to config file (default: ~/.config/karr-foundation/config.yml)',
88 );
89  
90 option command => (
91 is => 'ro',
92 format => 's',
93 doc => 'Global agent command; overrides .karr file per-repo',
94 );
95  
96 option force => (
97 is => 'ro',
98 doc => 'Run agent even if no board change detected and no open tasks; '
99 . 'answer: replace an answer that is already there; plan: replace a '
100 . 'chain that still has a step running',
101 );
102  
103 option dry_run => (
104 is => 'ro',
105 doc => 'Print what would run without executing; plan: check a chain and '
106 . 'write nothing',
107 );
108  
109 option verbose => (
110 is => 'ro',
111 doc => 'Extra output',
112 );
113  
114 option status => (
115 is => 'ro',
116 doc => 'Print a read-only overview of every board and exit (no agent runs)',
117 );
118  
119 # The question mailbox (#191). These belong to the `ask` and `answer` commands
120 # and are ignored by a drain, which is why their doc strings say which command
121 # reads them: this CLI has no per-command option namespace and inventing one
122 # for two commands would cost more than the prefix in the help text.
123 option context => (
124 is => 'ro',
125 format => 's',
126 doc => 'ask: prose context for the question',
127 );
128  
129 option options => (
130 is => 'ro',
131 format => 's',
132 doc => 'ask: comma-separated answers the question offers',
133 );
134  
135 option default => (
136 is => 'ro',
137 format => 's',
138 doc => 'ask: the answer to fall back on (needs --policy use_default)',
139 );
140  
141 option policy => (
142 is => 'ro',
143 format => 's',
144 doc => 'ask: what happens when nobody answers: block (default), '
145 . 'use_default, escalate_to_ai',
146 );
147  
148 option wait => (
149 is => 'ro',
150 format => 'i',
151 doc => 'ask: seconds before the policy takes over',
152 );
153  
154 option step => (
155 is => 'ro',
156 format => 's',
157 doc => 'ask: the chain step waiting on the answer',
158 );
159  
160 option note => (
161 is => 'ro',
162 format => 's',
163 doc => 'answer: a note to record beside the answer',
164 );
165  
166 option input => (
167 is => 'ro',
168 format => 's',
169 doc => 'plan: read the chain document from a file instead of stdin',
170 );
171  
172 has _stream_to_terminal => (
173 is => 'lazy',
174 builder => sub { -t STDOUT || $_[0]->verbose },
175 );
176  
177 # The config file this run reads, whether or not it exists. Its own attribute
178 # because it is more than the source of _config_data: the per-machine agent
179 # availability lives beside it (App::karr::Foundation::Agents), so --config
180 # relocates that too.
181 has _config_path => (
182 is => 'lazy',
183 builder => '_build_config_path',
184 );
185  
186 sub _build_config_path {
187 my ( $self ) = @_;
188 return defined $self->config
189 ? path( $self->config )
190 : path( $ENV{HOME} )->child( '.config', 'karr-foundation', 'config.yml' );
191 }
192  
193 has _config_data => (
194 is => 'lazy',
195 builder => '_build_config_data',
196 );
197  
198 sub _build_config_data {
199 my ( $self ) = @_;
200 my $cfg_path = $self->_config_path;
201  
202 unless ( $cfg_path->exists ) {
203 warn "karr-foundation: config not found at $cfg_path -- nothing to do\n";
204 return {};
205 }
206  
207 # Both of these are "your config is wrong", not "karr is wrong", so neither
208 # gets a Carp call site pointing into this file (#77). YAML::XS's own error
209 # names the document, line and column and carries no call site of its own, so
210 # it goes through whole rather than through clean_error, which would keep
211 # only its "YAML::XS::Load Error: The problem:" header.
212 my $data = try {
213 YAML::XS::LoadFile("$cfg_path");
214 } catch {
215 user_error("Cannot parse config $cfg_path: $_");
216 };
217 user_error("Config must be a YAML mapping") unless ref $data eq 'HASH';
218 return $data;
219 }
220  
221 # Collaborators split out of this module along its natural seams (see the
222 # App::karr::Foundation::* classes). Each holds a weak back-reference to this
223 # foundation for shared options/helpers; delegation keeps the historical
224 # method names callable directly on the foundation object.
225  
226 has _runner => (
227 is => 'lazy',
228 handles => [qw(
229 _run_command _error_patterns _match_error
230 _run_result _result_error _result_summary _result_line
231 )],
232 );
233  
234 sub _build__runner {
235 my ( $self ) = @_;
236 return App::karr::Foundation::Runner->new( foundation => $self );
237 }
238  
239 has _state => (
240 is => 'lazy',
241 handles => [qw(
242 _lock_held _acquire_lock _release_lock _force_release_lock
243 _read_lock_metadata
244 _state_get _state_set _state_del
245 _cooldown_active _set_cooldown _clear_cooldown
246 _bump_attempts _reset_attempts
247 )],
248 );
249  
250 sub _build__state {
251 my ( $self ) = @_;
252 return App::karr::Foundation::State->new( foundation => $self );
253 }
254  
255 has _agents => (
256 is => 'lazy',
257 );
258  
259 sub _build__agents {
260 my ( $self ) = @_;
261 return App::karr::Foundation::Agents->new( foundation => $self );
262 }
263  
264 # The judgement layer (#210): the coordination agent, the deviations that want
265 # it, and the assignment it writes so that routing needs no AI in the hot path.
266 # Lazy and mostly a no-op -- a fleet whose config marks no agent
267 # `role: coordinator` records nothing here and calls nothing.
268 has _coordinator => (
269 is => 'lazy',
270 );
271  
272 sub _build__coordinator {
273 my ( $self ) = @_;
274 return App::karr::Foundation::Coordinator->new( foundation => $self );
275 }
276  
277 has _overview => (
278 is => 'lazy',
279 handles => [qw( _print_overview )],
280 );
281  
282 sub _build__overview {
283 my ( $self ) = @_;
284 return App::karr::Foundation::Overview->new( foundation => $self );
285 }
286  
287 has _limits => (
288 is => 'lazy',
289 );
290  
291 sub _build__limits {
292 my ( $self ) = @_;
293 return App::karr::Foundation::Limits->new( foundation => $self );
294 }
295  
296 # The hub repository, or undef when no hub is configured. One repository of a
297 # fleet carries refs/karr-foundation/* -- the chain of planned steps, the run
298 # logs, the question mailbox -- and which one that is is a property of this
299 # machine's view of the fleet, so it is named locally rather than discovered. A
300 # hub that is not there is a warning and not an error: everything foundation
301 # does without a chain it still does. The two stores below share this one
302 # resolution because they share the repository; a second copy of it would be a
303 # second thing to keep in step with `hub:`.
304 has _hub_git => (
305 is => 'lazy',
306 );
307  
308 sub _build__hub_git {
309 my ( $self ) = @_;
310 my $hub = $self->_config_data->{hub};
311 return undef unless defined $hub && length $hub;
312 my $dir = path( $hub );
313 unless ( $dir->is_dir ) {
314 warn "karr-foundation: hub not found: $hub\n";
315 return undef;
316 }
317 my $git = App::karr::Git->new( dir => "$dir" );
318 unless ( $git->is_repo ) {
319 warn "karr-foundation: hub is not a git repository: $hub\n";
320 return undef;
321 }
322 return $git;
323 }
324  
325 # The chain of planned steps and the run logs (#189).
326 has _chain_store => (
327 is => 'lazy',
328 );
329  
330 sub _build__chain_store {
331 my ( $self ) = @_;
332 my $git = $self->_hub_git or return undef;
333 return App::karr::Foundation::ChainStore->new( git => $git );
334 }
335  
336 # The chain executor (#202): the layer above the repo modes that takes a ready
337 # step, checks its precheck, runs it through one of those modes and writes its
338 # state back. Built lazily and only reached by the `chain` command -- an
339 # ordinary tick drains boards and executes no step, because a cron entry
340 # written before the fleet had a chain must not start doing something else the
341 # day somebody writes one.
342 has _executor => (
343 is => 'lazy',
344 );
345  
346 sub _build__executor {
347 my ( $self ) = @_;
348 return App::karr::Foundation::Executor->new( foundation => $self );
349 }
350  
351 # The question mailbox, in the same repository and for the same reason: a
352 # question is coordination, so it lives where every machine can see it (#191).
353 has _questions => (
354 is => 'lazy',
355 );
356  
357 sub _build__questions {
358 my ( $self ) = @_;
359 my $git = $self->_hub_git or return undef;
360 return App::karr::Foundation::Questions->new( git => $git );
361 }
362  
363 # Open file descriptors that hold flock(2) locks on .karr.lock files for the
364 # boards currently being drained. The fd is what keeps the lock — closing it
365 # would drop the flock immediately, so Foundation keeps it for the lifetime
366 # of the drain. _keep_lock_fh / _take_lock_fh are the only writers/readers.
367 has _lock_fhs => (
368 is => 'ro',
369 default => sub { {} },
370 );
371  
372 # The agent process this run currently has on the board: { repo, pid, pgid,
373 # lockfile }. Set by the runner immediately after fork, cleared by the drain
374 # after waitpid. The SIGTERM handler in run() reads it to know what to kill.
375 # Undef between agents — the handler is a no-op on those gaps.
376 has _live_agent => (
377 is => 'rw',
378 default => sub { undef },
379 );
380  
381 # The boards this run currently has a forked child on: pid => the plan entry
382 # for that board. Only the concurrent runner writes it, and only in the parent
383 # -- a child clears it the moment it is born, or its inherited SIGTERM handler
384 # would kill its siblings' agents (see _spawn_repo). Empty in the serial
385 # runner, which is what makes the handler's two halves exclusive rather than
386 # additive.
387 has _live_children => (
388 is => 'ro',
389 default => sub { {} },
390 );
391  
392 # fd stash accessors used by State.pm — kept private to the foundation/state
393 # pair because they leak the internal "lock = open fd" model. Nobody else
394 # should care.
395 sub _keep_lock_fh {
396 my ( $self, $repo, $fh ) = @_;
397 $self->_lock_fhs->{ "$repo" } = $fh;
398 return;
399 }
400  
401 sub _take_lock_fh {
402 my ( $self, $repo ) = @_;
403 my $key = "$repo";
404 my $fh = delete $self->_lock_fhs->{$key};
405 return $fh;
406 }
407  
408  
409 # ---------------------------------------------------------------------------
410 # Public
411 # ---------------------------------------------------------------------------
412  
413 sub run {
414 my ( $self, @argv ) = @_;
415  
416 # The mailbox commands come first and never discover a board: a question is
417 # fleet state in the hub, and `karr-foundation answer 7 yes` typed by a person
418 # has nothing to do with which repositories this machine drains (#191).
419 if ( @argv ) {
420 my $command = shift @argv;
421 return $self->_run_ask(@argv) if $command eq 'ask';
422 return $self->_run_answer(@argv) if $command eq 'answer';
423 return $self->_run_chain(@argv) if $command eq 'chain';
424 return $self->_run_plan(@argv) if $command eq 'plan';
425 # "Unknown command:" is the marker App::karr::Error::is_usage_error keys on,
426 # so a typo here exits 2 (you called this wrong) and not 1 (ADR 0002).
427 user_error("Unknown command: '$command' (expected: answer, ask, chain, plan)");
428 }
429  
430 my @repos = $self->_discover_repos;
431 unless ( @repos ) {
432 warn "karr-foundation: no repos found -- check config\n";
433 return 1;
434 }
435  
436 # --status forces the read-only overview regardless of agent config.
437 if ( $self->status ) {
438 $self->_print_overview( \@repos );
439 return 0;
440 }
441  
442 # foundation is a multi-board coordinator: agent execution is opt-in. When no
443 # board has an agent configured, the default action is the overview — a human
444 # can use foundation purely to see what is happening across boards. A board
445 # disabled in its own karr state never counts as an agent board here either,
446 # so a config of nothing but disabled boards falls back to the overview.
447 # _plan_repos answers that per board, and the answer is kept: the concurrent
448 # runner needs the agent name out of the same resolution to bucket its
449 # per-agent limits, and resolving twice would be two chances to disagree.
450 my @plan = $self->_plan_repos( @repos );
451 unless ( grep { $_->{runs_agent} } @plan ) {
452 print "No agent will run on any board. Showing overview "
453 . "(set 'command:', 'agent:' or 'claude: true' in a .karr file to "
454 . "enable agents; a board disabled with 'karr disable' never runs "
455 . "one).\n\n";
456 $self->_print_overview( \@repos );
457 # And still the one call the tick may make (#210): a fleet whose boards
458 # are routed by an assignment that does not exist yet reaches exactly this
459 # branch -- no board resolves an agent, because nothing has said which one
460 # -- and it is the branch that most needs the coordination agent.
461 $self->_coordinator->dispatch;
462 return 0;
463 }
464  
465 # The fleet namespace, before anything reads it (#190). The chain is shared
466 # state and this machine's copy of it is only as good as its last fetch, so a
467 # tick that decided how much to run from a stale header would be deciding
468 # from a plan somebody has already replaced. Nothing is pushed back here:
469 # this run reads the chain header and writes no step state.
470 $self->_sync_pull_foundation;
471  
472 # SIGTERM/SIGINT/SIGHUP mid-drain used to leave the agent reparented to init
473 # and the .karr.lock naming a dead pid, and the next cron tick read the dead
474 # pid as free and started a second agent on the same board (#163, #148).
475 # The handler kills the agent's process group, releases the lock, and exits
476 # non-zero — the same exit shape systemd/cron see on any other failure, so
477 # the operator's monitoring does not need a special case for "killed cleanly
478 # mid-drain". Installed for the lifetime of run() and restored to default on
479 # the way out so a stray post-run signal goes to the OS, not back into us.
480 $self->_install_signal_handlers;
481  
482 # One board after another unless the machine ceiling says otherwise, which is
483 # what it says by default (App::karr::Foundation::Limits). --dry-run stays
484 # serial whatever the ceiling: it starts no agent, so concurrency would buy
485 # nothing and cost the deterministic order its output is read in.
486 my $concurrent = $self->dry_run ? 1 : $self->_limits->concurrent;
487 if ( $concurrent > 1 ) {
488 $self->_run_concurrent( \@plan, $concurrent );
489 }
490 else {
491 $self->_run_serially( map { $_->{repo} } @plan );
492 }
493  
494 # The judgement layer, last and once (#210). Last, because a planner called
495 # half way through would plan against a board this tick's own agents were
496 # still moving; once, because a tick that met five deviations has learned one
497 # thing and five calls would pay five times to hear it. Before the handlers
498 # go back to default: the coordination agent is a forked agent like any
499 # other, and a signal arriving during it has to take it down with us.
500 $self->_coordinator->dispatch;
501  
502 $self->_restore_default_signal_handlers;
503 return 0;
504 }
505  
506 # ---------------------------------------------------------------------------
507 # The question mailbox (#191)
508 # ---------------------------------------------------------------------------
509  
510 # The mailbox lives in the hub, so a machine without one has nowhere to put a
511 # question. That is an error and not a warning: the two commands do exactly one
512 # thing, and doing it locally where nobody would ever read it is not a smaller
513 # version of it.
514 sub _mailbox {
515 my ( $self ) = @_;
516 return $self->_questions // user_error(
517 'No usable hub repository: the question mailbox lives in '
518 . 'refs/karr-foundation/questions/* in the fleet hub, so name one with '
519 . "'hub: /path/to/repo' in " . $self->_config_path );
520 }
521  
522 # A mailbox that does not travel is a notepad, and neither does a plan. `ask`
523 # pulls before it mints an id -- ids are minted from what this clone can see,
524 # so the pull is what keeps two machines from picking the same one -- `plan`
525 # pulls before it measures whether the chain it replaces still has a step
526 # running, and all three push what they wrote. A transport failure is a
527 # warning: the ref is written locally either way and the next `karr sync` in
528 # the hub publishes it, which is a better answer than refusing to record a
529 # question because the network is down. `chain` is the one command that
530 # refuses instead, because the fallback there is running a step another
531 # machine is already running.
532 sub _namespace_sync {
533 my ( $self, $verb ) = @_;
534 my $git = $self->_hub_git or return;
535 my $method = "${verb}_foundation";
536 try {
537 $git->$method;
538 } catch {
539 warn "karr-foundation: $verb of refs/karr-foundation/ failed: "
540 . clean_error($_) . "\n";
541 };
542 return;
543 }
544  
545 # --options a,b, the same comma-separated spelling `karr create --tags` uses,
546 # with the whitespace around a comma allowed: `--options "cpan, darkpan"` is
547 # what a person types and refusing it would teach nothing.
548 sub _option_list {
549 my ( $self, $value ) = @_;
550 return () unless defined $value;
551 my @options = grep { length }
552 map { my $o = $_; $o =~ s/\A\s+|\s+\z//g; $o } split /,/, $value;
553 return @options ? ( options => \@options ) : ();
554 }
555  
556 sub _run_ask {
557 my ( $self, @argv ) = @_;
558 user_error( 'Usage: karr-foundation ask QUESTION [--context PROSE] '
559 . '[--options a,b] [--default a] [--policy block|use_default|escalate_to_ai] '
560 . '[--wait SECONDS] [--step ID]: quote a question that contains spaces' )
561 unless @argv == 1 && defined $argv[0] && length $argv[0];
562  
563 my $mailbox = $self->_mailbox;
564 $self->_namespace_sync('pull');
565  
566 my $id = $mailbox->ask(
567 question => $argv[0],
568 $self->_option_list( $self->options ),
569 ( defined $self->context ? ( context => $self->context ) : () ),
570 ( defined $self->default ? ( default => $self->default ) : () ),
571 ( defined $self->policy ? ( policy => $self->policy ) : () ),
572 ( defined $self->wait ? ( wait => $self->wait ) : () ),
573 ( defined $self->step ? ( step => $self->step ) : () ),
574 );
575 $self->_namespace_sync('push');
576  
577 # The id and the command that settles it, because the next thing whoever
578 # reads this does is answer it -- from a terminal that has none of the
579 # context this one has.
580 my $q = $mailbox->question($id);
581 printf "Asked question #%s: %s\n", $id, $q->{question};
582 printf " answer with: karr-foundation answer %s <%s>\n", $id,
583 ( $q->{options} ? join( '|', @{ $q->{options} } ) : 'answer' );
584 printf " nobody answers: %s%s\n", $q->{policy},
585 ( defined $q->{deadline} ? " after $q->{deadline}" : '' );
586 return 0;
587 }
588  
589 # The chain (#202). A command of its own, not something an ordinary tick picks
590 # up on the side: `karr-foundation` with no arguments has meant "drain the
591 # boards in my config" since it existed, and the day somebody wrote a chain into
592 # the hub every cron entry in the fleet would silently have started doing
593 # something else. Opting into execution is the rule agent execution itself
594 # follows here, and the chain is a bigger opt-in, not a smaller one.
595 sub _run_chain {
596 my ( $self, @argv ) = @_;
597 user_error( 'Usage: karr-foundation chain [--dry-run] [--verbose]'
598 . ': the chain takes no arguments; what runs is what the plan in '
599 . 'the hub says is ready' ) if @argv;
600 my $exit = $self->_executor->run;
601 # The three chain-side deviations -- a kind: plan step, an escalate_to_ai
602 # question, a step gone stale -- are recorded by the executor as it meets
603 # them and answered here, once, after the tick has worked through everything
604 # it could (#210). The exit code is the executor's either way: whether a
605 # planner was called says nothing about whether this binary did its job.
606 $self->_coordinator->dispatch;
607 return $exit;
608 }
609  
610 # ---------------------------------------------------------------------------
611 # Writing the chain (#213)
612 # ---------------------------------------------------------------------------
613  
614 # The chain had no command of its own: App::karr::Foundation::ChainStore's
615 # write_chain was Perl API, so the one writer that is not a person -- the
616 # coordination agent -- was handed a `perl -MApp::karr::Foundation::ChainStore
617 # -e ...` one-liner in its prompt and asked to type it out. That made a storage
618 # API somebody's interface, where everything else karr asks an agent to do is a
619 # command, and it meant a rename inside that class broke a prompt rather than a
620 # call: silently, and only on the tick where a plan was wanted.
621 #
622 # It takes a document rather than options because a chain is a DAG and a DAG is
623 # nested: `--step id=1,kind=ticket,needs=2,3` would be YAML with a worse syntax
624 # and a parser of its own, and the writer that matters most already produces
625 # structure. Stdin (or --input) is where `karr restore` takes a snapshot from,
626 # for the same reason, and the document is read as YAML -- which reads JSON
627 # too, so an agent that emits JSON has emitted a chain document.
628 #
629 # It replaces the chain rather than adding to it, because that is what
630 # write_chain does and what the header means: ready_steps only considers steps
631 # whose chain id matches the header, so "append" would be a new chain id over
632 # the old steps plus the new ones -- a merge with its own rules about ids that
633 # already exist and states that were already reached. The plan is what the
634 # planner currently thinks; a chain that still has a running step is refused
635 # unless --force, which is the guard that makes replacing safe.
636 sub _run_plan {
637 my ( $self, @argv ) = @_;
638 user_error( 'Usage: karr-foundation plan [--input PATH] [--force] '
639 . '[--dry-run]: the chain itself arrives as YAML or JSON on stdin, or '
640 . 'from the file --input names' ) if @argv;
641  
642 # The chain is fleet state, so a machine without a hub has nowhere to put
643 # one. The same error the mailbox commands raise, for the same reason:
644 # writing a plan only this clone can see is not a smaller version of writing
645 # the fleet's plan.
646 my $store = $self->_chain_store // user_error(
647 'No usable hub repository: the chain lives in '
648 . 'refs/karr-foundation/chain/* in the fleet hub, so name one with '
649 . "'hub: /path/to/repo' in " . $self->_config_path );
650  
651 # Parsed before the network is touched, so a document that is not one costs
652 # nothing; the steps themselves are checked by the store, which is where the
653 # step schema lives and where the write path checks them anyway.
654 my ( $steps, %header ) = $store->parse_chain_document( $self->_chain_document );
655 my $force = $self->force ? 1 : 0;
656  
657 # Before either path: the guard against replacing a chain that still has a
658 # running step is only as good as this machine's copy of that chain.
659 $self->_namespace_sync('pull');
660  
661 if ( $self->dry_run ) {
662 my $validated = $store->validate_chain( $steps, force => $force );
663 print 'The chain is valid: ' . scalar(@$validated)
664 . " step(s), nothing written (--dry-run)\n";
665 print _plan_step_lines(@$validated);
666 return 0;
667 }
668  
669 my $chain_id = $store->write_chain( $steps, %header, force => $force );
670 $self->_namespace_sync('push');
671  
672 # Read back rather than echoed: what is printed is what is in the hub, in
673 # the order every other reader of the chain sees it.
674 my @written = $store->steps;
675 print "Wrote chain $chain_id: " . scalar(@written) . " step(s)\n";
676 print _plan_step_lines(@written);
677 print " execute it with: karr-foundation chain\n";
678 return 0;
679 }
680  
681 # The steps as lines: what each one is, where it happens, and what it waits
682 # for -- the three things somebody reading back a chain they have just written
683 # checks it against. The ids share a column so the kinds line up under each
684 # other, which is what makes a mistyped kind visible at a glance.
685 sub _plan_step_lines {
686 my ( @steps ) = @_;
687 my $width = 0;
688 for my $step ( @steps ) {
689 my $len = length "$step->{id}";
690 $width = $len if $len > $width;
691 }
692 my @lines;
693 for my $step ( @steps ) {
694 my @what = ( defined $step->{ticket}
695 ? "$step->{kind} #$step->{ticket}" : $step->{kind} );
696 push @what, "in $step->{repo}" if defined $step->{repo};
697 push @what, 'needs ' . join( ', ', @{ $step->{needs} } )
698 if $step->{needs} && @{ $step->{needs} };
699 push @lines, sprintf " %-*s %s\n", $width, $step->{id}, join( ', ', @what );
700 }
701 return @lines;
702 }
703  
704 # The document as characters, from --input or from stdin.
705 sub _chain_document {
706 my ( $self ) = @_;
707 my $payload;
708  
709 if ( defined $self->input ) {
710 # An unreadable --input is the caller's path, not karr's: Path::Tiny's own
711 # error would hand them this file and line instead (#77).
712 $payload = try { path( $self->input )->slurp_utf8 }
713 catch {
714 user_error( 'Could not read ' . $self->input . ': ' . clean_error($_) );
715 };
716 }
717 else {
718 # A terminal has nothing queued and would sit there with no prompt, so the
719 # invocation that forgot its input stays a usage error instead of becoming
720 # a hang -- the reading App::karr::Cmd::SetRefs makes of the same edge.
721 user_error( 'Usage: karr-foundation plan < chain.yml: the chain '
722 . 'document arrives on stdin, or from the file --input names' )
723 if -t STDIN;
724  
725 # STDIN is the one input edge App::karr::Encoding leaves without a PerlIO
726 # layer, precisely so this decode is explicit and happens exactly once.
727 binmode STDIN, ':raw';
728 my $octets = do { local $/; <STDIN> };
729  
730 # An empty stdin is not an empty chain: a generator upstream that produced
731 # nothing is a mistake, and a chain needs at least one step anyway. A
732 # runtime failure and not a usage error -- the invocation was right, what
733 # arrived on the pipe was not.
734 user_error('No chain document received on stdin')
735 unless defined $octets && length $octets;
736 $payload = from_octets($octets);
737 }
738  
739 my $doc = try { yaml_load($payload) }
740 catch {
741 # Through whole rather than through clean_error, the same way the config
742 # loader above takes YAML::XS's errors: it names the document, the line and
743 # the column and carries no call site of its own, and clean_error would
744 # keep only its "YAML::XS::Load Error: The problem:" header -- which tells
745 # the writer of a broken chain nothing at all.
746 user_error("The chain document is not valid YAML or JSON: $_");
747 };
748 user_error('The chain document is empty') unless defined $doc;
749 return $doc;
750 }
751  
752 sub _run_answer {
753 my ( $self, @argv ) = @_;
754 user_error( 'Usage: karr-foundation answer ID ANSWER [--note TEXT] '
755 . '[--force]: quote an answer that contains spaces' )
756 unless @argv == 2 && defined $argv[1] && length $argv[1];
757  
758 my $mailbox = $self->_mailbox;
759 $self->_namespace_sync('pull');
760  
761 my $a = $mailbox->settle( $argv[0], $argv[1],
762 ( defined $self->note ? ( note => $self->note ) : () ),
763 force => ( $self->force ? 1 : 0 ),
764 );
765 $self->_namespace_sync('push');
766  
767 printf "Answered question #%s: %s\n", $a->{id}, $a->{answer};
768 printf " %s\n", $a->{question};
769 return 0;
770 }
771  
772 # What each discovered repo is going to do this tick, decided once in the
773 # parent: whether it is disabled, whether an agent is meant to run on it at
774 # all, and -- where the command came from a named definition -- which agent,
775 # because that is the bucket the per-agent concurrency limit counts in. It is
776 # the same work run() has always done to choose between the overview and a run;
777 # the concurrent scheduler needs the agent name out of the same resolution, so
778 # it is computed once and handed on rather than resolved twice.
779 sub _plan_repos {
780 my ( $self, @repos ) = @_;
781 my @plan;
782 for my $repo ( @repos ) {
783 my %p = ( repo => $repo );
784 push( @plan, \%p ), next if $self->_board_disabled( $repo );
785 try {
786 my ( $cmd, $inv, $wait ) = $self->_resolve_agent( $repo, $self->_load_karr( $repo ) );
787 if ( defined $wait ) {
788 # An agent board whose assignment says wait (#210). It counts as an
789 # agent board -- it is one, and the overview fallback is for a config
790 # with no agents at all, not for one whose agents are down -- and it
791 # gets no fork: _process_repo says the skip and there is nothing to
792 # spend a concurrency slot on. Exactly what a board in cooldown does.
793 $p{runs_agent} = 1;
794 }
795 elsif ( defined $cmd ) {
796 $p{runs_agent} = 1;
797 $p{fork} = 1;
798 $p{agent} = $inv->{name} if $inv;
799 }
800 }
801 catch {
802 # A board naming an agent this config does not define. _process_repo is
803 # where that gets reported (run()'s per-repo catch turns it into a
804 # warning and skips one board), so here it only says "an agent was meant
805 # to run" -- enough to keep it out of the overview fallback, not enough
806 # to spend a concurrency slot on a board that will start nothing.
807 $p{runs_agent} = 1;
808 };
809 push @plan, \%p;
810 }
811 return @plan;
812 }
813  
814 sub _run_serially {
815 my ( $self, @repos ) = @_;
816 for my $repo ( @repos ) {
817 try {
818 $self->_process_repo( $repo );
819 } catch {
820 warn "karr-foundation: error in $repo: $_\n";
821 };
822 }
823 return;
824 }
825  
826 # Several boards at once, one agent per board. The unit of concurrency is a
827 # forked child that runs the whole of _process_repo for exactly one repo, which
828 # is what keeps the one hard rule intact: .karr.lock stays per repository, and
829 # a board is held by the single child that took it for the length of its drain.
830 # Two agents in one working tree would collide over the index and the checkout,
831 # so concurrency here is across repositories and never inside one -- anything
832 # else needs a git worktree per agent and is deliberately out of scope.
833 #
834 # Forking the whole per-repo pass, rather than teaching the drain loop to
835 # interleave several agents, is the cheap half of that rule: every piece of
836 # per-board state -- the lock fd, .karr.state, the engagement record, the
837 # attempt counters -- keeps exactly one writer without a line of it changing.
838 # The state that is genuinely shared is agents.state, and that one is locked
839 # (App::karr::Foundation::Agents).
840 sub _run_concurrent {
841 my ( $self, $plan, $max ) = @_;
842 my $per = $self->_limits->per_agent;
843  
844 # Everything that will not start an agent is done here, in order, before the
845 # first fork: a disabled board, a board with no agent, a board naming one
846 # this config does not define. Each costs a couple of ref reads and produces
847 # a skip line; forking for it would spend a slot on a no-op and scatter those
848 # lines through the agent output for nothing.
849 my @queue;
850 for my $item ( @$plan ) {
851 push( @queue, $item ), next if $item->{fork};
852 $self->_run_serially( $item->{repo} );
853 }
854  
855 my $live = $self->_live_children;
856 my %busy;
857  
858 while ( @queue || %$live ) {
859 my $started = 0;
860  
861 if ( keys %$live < $max ) {
862 # Scanned rather than shifted: a board whose agent is at its own limit is
863 # passed over, not waited for. Head-of-line blocking here would let one
864 # busy agent idle the whole machine while boards on another agent wait.
865 for my $i ( 0 .. $#queue ) {
866 my $name = $queue[$i]{agent};
867 next if defined $name
868 && defined $per->{$name}
869 && ( $busy{$name} // 0 ) >= $per->{$name};
870 my ( $item ) = splice @queue, $i, 1;
871 $started = 1;
872 my $pid = $self->_spawn_repo( $item ) or last;
873 $live->{$pid} = $item;
874 $busy{$name}++ if defined $name;
875 last;
876 }
877 }
878  
879 next if $started;
880  
881 unless ( %$live ) {
882 # Nothing running, nothing startable: every queued board is held by a
883 # per-agent limit no running child will ever give back. A positive limit
884 # cannot produce this -- an empty bucket is always under one -- so this
885 # is the guard for a zero that got past validation, and it says so
886 # instead of spinning.
887 warn 'karr-foundation: ' . scalar(@queue)
888 . " board(s) left unrun -- no concurrency slot can free up\n";
889 last;
890 }
891  
892 my $pid = waitpid -1, 0;
893 last if $pid <= 0;
894 my $done = delete $live->{$pid} or next;
895 my $name = $done->{agent};
896 $busy{$name}-- if defined $name && $busy{$name};
897 }
898 return;
899 }
900  
901 # Fork one child for one board. Returns the child's pid in the parent and never
902 # returns in the child.
903 sub _spawn_repo {
904 my ( $self, $item ) = @_;
905 my $repo = $item->{repo};
906  
907 # Anything still in a buffer would be written twice -- once by the parent
908 # when it flushes, once by the child that inherited the same buffer.
909 STDOUT->flush;
910 STDERR->flush;
911  
912 my $pid = fork;
913 unless ( defined $pid ) {
914 warn "karr-foundation: fork failed for $repo: $!\n";
915 return undef;
916 }
917 return $pid if $pid;
918  
919 # ----- child: it owns exactly this one board -----
920 #
921 # The parent's bookkeeping is the parent's. A child that kept the inherited
922 # sibling list would kill its siblings' agents out of the SIGTERM handler it
923 # also inherited, and a child that kept the inherited lock fds would release
924 # locks it never took.
925 %{ $self->_live_children } = ();
926 %{ $self->_lock_fhs } = ();
927 $self->_live_agent( undef );
928  
929 my $ok = try {
930 $self->_process_repo( $repo );
931 1;
932 } catch {
933 warn "karr-foundation: error in $repo: $_\n";
934 0;
935 };
936  
937 # _exit, not exit: END blocks and global destruction belong to the process
938 # that set them up. Running them in a forked copy would flush the parent's
939 # buffers a second time and tear libgit2 down from a child that only borrowed
940 # it -- the re-entrancy App::karr::Git refuses outright at teardown (#34).
941 # _exit does not flush, so the flush is by hand.
942 STDOUT->flush;
943 STDERR->flush;
944 POSIX::_exit( $ok ? 0 : 1 );
945 }
946  
947 # SIGTERM/INT/HUP handler: kill the live agent's process group, release the
948 # lock, exit non-zero. Built once at run() time and shared by all three
949 # signals — the OS's default for SIGINT/SIGHUP is exit too, but those do not
950 # wait for the agent to die, which is the whole problem.
951 sub _install_signal_handlers {
952 my ( $self ) = @_;
953 my $handler = sub { $self->_handle_shutdown_signal(@_); };
954 $SIG{TERM} = $handler;
955 $SIG{INT} = $handler;
956 $SIG{HUP} = $handler;
957 return;
958 }
959  
960 sub _restore_default_signal_handlers {
961 $SIG{TERM} = 'DEFAULT';
962 $SIG{INT} = 'DEFAULT';
963 $SIG{HUP} = 'DEFAULT';
964 return;
965 }
966  
967 # Signal handler body. Perl signal handlers run in a restricted context — no
968 # malloc, no PerlIO ops beyond safe ones, and certainly no $self->method on an
969 # object whose class might be in the middle of compilation. Foundation is
970 # already running and the methods called here are simple attribute reads and
971 # POSIX ops, which are documented as safe in 5.16+. We do NOT call
972 # Foundation's own _append_log or anything that opens files — the agent is
973 # dying and the lock is going away; the operator gets the next run's log.
974 sub _handle_shutdown_signal {
975 my ( $self, $sig_name ) = @_;
976 my $agent = $self->_live_agent;
977 if ( $agent && $agent->{pgid} ) {
978 # Negative pid = process group (kill(2) group semantics). The agent's
979 # pgid is the agent's own pid because Runner calls setpgrp(0,0) in the
980 # child right after fork, so kill 'TERM', -$pgid signals the whole group
981 # — including any grandchildren the agent itself forked (#148).
982 kill 'TERM', -$agent->{pgid};
983 # Give the group a moment to die. SIGTERM is catchable; a hung child
984 # needs SIGKILL. Two seconds matches the timeout path in Runner.
985 my $end = time + 2;
986 while ( time < $end ) {
987 last if kill( 0, $agent->{pid} ) == 0;
988 select undef, undef, undef, 0.05;
989 }
990 kill 'KILL', -$agent->{pgid};
991 # Reap without blocking — the SIGKILL will deliver but the actual wait
992 # is best-effort because we are already on the way out.
993 waitpid $agent->{pid}, 0 if $agent->{pid};
994 }
995 if ( $agent && $agent->{repo} ) {
996 # Force-release the lock: we may have lost the fd through a process
997 # restart, but the recorded pid in the file still matches $$ if this is
998 # the foundation that took it. _force_release_lock verifies and unlinks.
999 # Wrap the repo argument in path() in case it crossed a string boundary
1000 # (some callers keep agent->{repo} as a string); State.pm's helpers all
1001 # take a Path::Tiny object.
1002 $self->_force_release_lock( path( $agent->{repo} ) );
1003 }
1004  
1005 # The concurrent runner's children (#186). Each inherited this same handler
1006 # and has its own agent on its own board, so the parent does not reach past
1007 # them: it TERMs the children and lets every one of them run the branch above
1008 # for its own board -- kill its agent's process group, release its own lock.
1009 # Killing the children outright instead would leave every agent reparented to
1010 # init, which is #163's failure multiplied by the concurrency. SIGKILL is
1011 # only for a child that did not manage even that.
1012 my $kids = $self->_live_children;
1013 if ( %$kids ) {
1014 kill 'TERM', keys %$kids;
1015 # Long enough for a child to finish its own two-second TERM-then-KILL on
1016 # the agent and unlink its lock; short enough that an operator holding
1017 # Ctrl-C does not conclude that nothing is happening.
1018 my $end = time + 5;
1019 while ( time < $end ) {
1020 for my $pid ( keys %$kids ) {
1021 delete $kids->{$pid} if waitpid( $pid, WNOHANG ) != 0;
1022 }
1023 last unless %$kids;
1024 select undef, undef, undef, 0.05;
1025 }
1026 if ( %$kids ) {
1027 kill 'KILL', keys %$kids;
1028 waitpid $_, 0 for keys %$kids;
1029 }
1030 }
1031 # Restore defaults so the second delivery (e.g. impatient operator) kills us
1032 # for real instead of looping in the handler.
1033 $self->_restore_default_signal_handlers;
1034 # Exit non-zero so cron/systemd can see we did not finish a clean run.
1035 # $sig_name is "TERM" / "INT" / "HUP" — 128 + signal number is the
1036 # conventional shell exit code for signal death.
1037 my $sig_num = $sig_name eq 'TERM' ? SIGTERM
1038 : $sig_name eq 'INT' ? SIGINT
1039 : $sig_name eq 'HUP' ? SIGHUP
1040 : 15;
1041 POSIX::_exit( 128 + $sig_num );
1042 }
1043  
1044  
1045 # ---------------------------------------------------------------------------
1046 # Discovery
1047 # ---------------------------------------------------------------------------
1048  
1049 sub _discover_repos {
1050 my ( $self ) = @_;
1051 my @repos;
1052  
1053 # Explicit repo roots
1054 for my $dir ( @{ $self->_config_data->{dirs} // [] } ) {
1055 my $p = path( $dir );
1056 if ( $p->is_dir ) {
1057 push @repos, $p;
1058 } else {
1059 warn "karr-foundation: dir not found: $dir\n";
1060 }
1061 }
1062  
1063 # Scanned parent directories — check direct children for .karr file
1064 # OR refs/karr/config (karr-init'd repo without .karr file)
1065 for my $scan_dir ( @{ $self->_config_data->{scan} // [] } ) {
1066 my $p = path( $scan_dir );
1067 unless ( $p->is_dir ) {
1068 warn "karr-foundation: scan dir not found: $scan_dir\n";
1069 next;
1070 }
1071 for my $child ( $p->children ) {
1072 next unless $child->is_dir;
1073 # .karr file takes precedence; also detect karr-init'd repos
1074 if ( $child->child('.karr')->exists ) {
1075 push @repos, $child;
1076 } elsif ( $self->_is_karr_board_root( $child ) ) {
1077 push @repos, $child;
1078 }
1079 }
1080 }
1081  
1082 # A repo reachable through both dirs: (explicit) and scan: (its parent) was
1083 # processed twice per tick — the agent ran twice and the overview printed
1084 # the board twice (#166). The two Path::Tiny objects can be the same string,
1085 # differ only by trailing slash, or even be a symlink and its target; the
1086 # key is the canonical filesystem path. First-seen wins so the explicit
1087 # dirs: order is preserved over whatever order scan: happened to find them.
1088 my %seen;
1089 my @uniq;
1090 for my $repo ( @repos ) {
1091 my $key = try { $repo->realpath } catch { $repo->absolute };
1092 next if $seen{$key}++;
1093 push @uniq, $repo;
1094 }
1095 return @uniq;
1096 }
1097  
1098 # True when $dir is *itself* the root of a karr-init'd repo — resolves via
1099 # libgit2 so packed refs (git gc / pack-refs) and worktree gitdir indirection
1100 # are handled, unlike a bare .git/refs/karr/config file check. libgit2's
1101 # open_ext walks up to find an enclosing .git, so a plain directory nested
1102 # inside a karr repo would spuriously match; guard by confirming the resolved
1103 # repo root is $dir, not an ancestor.
1104 sub _is_karr_board_root {
1105 my ( $self, $dir ) = @_;
1106 my $git = App::karr::Git->new( dir => "$dir" );
1107 return 0 unless $git->is_repo;
1108 my $root = $git->repo_root or return 0;
1109 return 0 unless $root->realpath eq path( $dir )->realpath;
1110 return $git->ref_exists('refs/karr/config');
1111 }
1112  
1113 # ---------------------------------------------------------------------------
1114 # Per-repo processing
1115 # ---------------------------------------------------------------------------
1116  
1117 # One pass over one repository. Returns the drain's own result hash, or
1118 # { outcome => 'skipped', reason => ... } for a repo this tick did not take up
1119 # at all -- a shape the serial and concurrent runners ignore and the chain
1120 # executor (#202) reads: a step whose board was locked, disabled, in cooldown or
1121 # on a failing agent is a step to try again, not a step that failed.
1122 #
1123 # %opt is the chain's half of the contract, and only the chain passes it:
1124 # `ticket` names the card this run is about (which forces ticket mode -- the
1125 # plan has already decided what this run is, whatever the .karr file's `mode`
1126 # says, and a chain step that named a card is by construction work to do, so it
1127 # needs no board-movement check to justify starting) and `timeout` is the
1128 # step's own budget for it.
1129 sub _process_repo {
1130 my ( $self, $repo, %opt ) = @_;
1131  
1132 # Check if repo has karr board (either .karr file or karr refs). Resolve the
1133 # ref via libgit2 so packed refs and worktrees are handled — $repo is an
1134 # already-known repo root here, so open_ext's walk-up cannot false-match.
1135 my $has_karr = $repo->child('.karr')->exists
1136 || App::karr::Git->new( dir => "$repo" )->ref_exists('refs/karr/config');
1137 unless ( $has_karr ) {
1138 $self->_say_verbose("skip $repo -- no karr board");
1139 return { outcome => 'skipped', reason => 'no karr board' };
1140 }
1141  
1142 # Board-level disable flag, checked FIRST: before the agent command is even
1143 # resolved and before the drain decision. A disabled board is skipped whole —
1144 # no drain, no auto-block, no agent run — so the flag wins over --command,
1145 # the config's default_command, the .karr command and 'claude: true'. It is
1146 # deliberately absolute: --force does not override it.
1147 return { outcome => 'skipped', reason => 'the board is disabled' }
1148 if $self->_skip_disabled( $repo );
1149  
1150 my $karr = $self->_load_karr( $repo );
1151  
1152 # Resolve the agent command (CLI > default_command > .karr command > a named
1153 # agent definition > the assignment > claude: true synthesis). Agent
1154 # execution is opt-in: a board with no agent is shown in the overview, not
1155 # run.
1156 my ( $cmd, $agent, $wait ) = $self->_resolve_agent( $repo, $karr );
1157  
1158 # The assignment routes this board and says nothing may run on it right now
1159 # (#210): every agent in its fallback chain is failing, or the chain says
1160 # WAIT. Skipped like a board in cooldown and for the same reason -- the wait
1161 # is bounded and ends by itself -- and NOT reported as "no agent configured",
1162 # which is a different board and a different fix.
1163 if ( defined $wait ) {
1164 $self->_say_verbose("skip $repo -- $wait");
1165 return { outcome => 'skipped', reason => $wait };
1166 }
1167  
1168 unless ( defined $cmd ) {
1169 $self->_say_verbose("skip $repo -- no agent configured (see --status)");
1170 return { outcome => 'skipped', reason => 'no agent configured' };
1171 }
1172  
1173 # Check lock — skip if another instance is running
1174 if ( $self->_lock_held( $repo ) ) {
1175 $self->_say_verbose("skip $repo -- locked by running agent");
1176 return { outcome => 'skipped', reason => 'the board lock is held' };
1177 }
1178  
1179 # Respect exponential cooldown left by a previous common-error run
1180 if ( $self->_cooldown_active( $repo ) ) {
1181 my $until = $self->_state_get( $repo, 'cooldown_until' ) // 0;
1182 $self->_say_verbose( "skip $repo -- in cooldown for " . ( $until - time ) . "s" );
1183 return { outcome => 'skipped',
1184 reason => 'the board is in cooldown for ' . ( $until - time ) . 's' };
1185 }
1186  
1187 # And the agent's own availability, which is the same idea one level up. The
1188 # cooldown above parks THIS BOARD after a bad run; this parks EVERY board
1189 # that uses the agent that had it, because "the command stopped working" is a
1190 # fact about the command and the machine, not about the repository. Two repos
1191 # driven by the same agent share the outage instead of each burning a window
1192 # discovering it. Like the cooldown, --force does not override it: the wait
1193 # is bounded by probe_every and ends by itself.
1194 if ( $agent && !$self->_agents->available( $agent->{name} ) ) {
1195 my $av = $self->_agents->availability( $agent->{name} );
1196 my $wait = ( $av->{next_attempt} // 0 ) - time;
1197 $self->_say_verbose( "skip $repo -- agent '$agent->{name}' failing"
1198 . ( defined $av->{last_error} ? " ($av->{last_error})" : '' )
1199 . ", next attempt in ${wait}s" );
1200 return { outcome => 'skipped',
1201 reason => "agent '$agent->{name}' is failing, next attempt in ${wait}s" };
1202 }
1203  
1204 # Pull latest refs. A pull that refuses -- the wholesale-wipe guard, the
1205 # board-identity guard, and (since #154) the unapplied-refs guard all die
1206 # rather than return false -- must not abort the drain loop. The other
1207 # per-repo step that can die (_drain_repo below) is wrapped in its own
1208 # try and turned into a structured error result; the pull sits at the same
1209 # level and is isolated the same way, so a refusal from one board warns
1210 # and is skipped here while the rest of run() continues to the next.
1211 # The pull happens before the lock is taken, so "release whatever it
1212 # holds" is a no-op today; the wrap is for the structural isolation
1213 # (clean separation, karr-shaped error message) and is forward-compatible
1214 # with any future caller that takes the lock before pulling.
1215 my $pull_ok = try {
1216 $self->_sync_pull( $repo );
1217 1;
1218 } catch {
1219 warn "karr-foundation: pull error in $repo: $_\n";
1220 0;
1221 };
1222 return { outcome => 'skipped', reason => 'the board could not be pulled' }
1223 unless $pull_ok;
1224  
1225 # The pull may have just brought the disable flag in from another machine —
1226 # re-check before committing to a drain, so a board disabled elsewhere is
1227 # never drained even once by this host.
1228 return { outcome => 'skipped', reason => 'the board is disabled' }
1229 if $self->_skip_disabled( $repo );
1230  
1231 # Decide whether to start a drain at all. A chain step naming a card is the
1232 # third answer beside --force and the board's own movement: the plan already
1233 # decided this run has something to do, and asking the board again could only
1234 # disagree with it.
1235 my $should_run = $self->force || defined $opt{ticket};
1236 unless ( $should_run ) {
1237 my $prev_hash = $self->_state_get( $repo, 'hash' ) // '';
1238 my $curr_hash = $self->_ref_hash( $repo ) // '';
1239 my $on_idle = $karr->{on_idle} // 'skip';
1240 $should_run = ( $curr_hash ne $prev_hash )
1241 || $self->_has_actionable_tasks( $repo )
1242 || ( $on_idle eq 'always-run' );
1243 }
1244  
1245 unless ( $should_run ) {
1246 $self->_say_verbose("skip $repo -- no board change and no actionable tasks");
1247 return { outcome => 'skipped',
1248 reason => 'no board change and no actionable tasks' };
1249 }
1250  
1251 # Acquire lock — flock-based now, so two ticks that overlap race on the
1252 # file rather than on a check-then-act gap a git pull apart (#162). Failure
1253 # here means another foundation instance holds the board; we skip and move
1254 # on instead of spewing over the existing lock.
1255 unless ( $self->_acquire_lock( $repo ) ) {
1256 $self->_say_verbose("skip $repo -- lock contended (another tick holds it)");
1257 return { outcome => 'skipped', reason => 'the board lock is contended' };
1258 }
1259 my $result = try {
1260 $self->_drain_repo( $repo, $karr, $cmd, $agent, %opt );
1261 } catch {
1262 warn "karr-foundation: drain error in $repo: $_\n";
1263 { outcome => 'error', exit => 1 };
1264 };
1265 # The domain hook, still under the board's own lock (#193). A release gate
1266 # that builds and installs out of this working tree must not have another
1267 # tick's agent walk into it halfway through, and .karr.lock is the thing
1268 # that already says "one process in this repository at a time". Isolated the
1269 # same way the drain and the pull above are: a hook that throws warns and is
1270 # skipped, because dying here would carry the _release_lock below with it
1271 # and leave the board locked by a process that is no longer in it.
1272 try {
1273 $self->_run_on_drained( $repo, $karr, $result );
1274 } catch {
1275 warn "karr-foundation: on_drained error in $repo: $_\n";
1276 };
1277 $self->_release_lock( $repo );
1278  
1279 # Exponential cooldown bookkeeping: grow on common-error, reset otherwise.
1280 # A run that was not a common error also drops last_error — it describes the
1281 # last run, and one left standing outlives the cooldown it caused and reads
1282 # as a contradiction against the last_exit written just below (#160).
1283 #
1284 # The same verdict updates the named agent's availability, for boards that
1285 # use one. Nothing finer is asked of it: a rate limit, a spent budget, a
1286 # revoked key and a wrapper that is not installed here all arrive as
1287 # common-error, and the same bounded retry answers all of them. A run that
1288 # was NOT a common error says the command works, which is what ends an
1289 # outage and gets the moment it ended written down. A false positive costs
1290 # one probe interval of caution; a false negative costs every board on that
1291 # agent its next window.
1292 if ( ( $result->{outcome} // '' ) eq 'common-error' ) {
1293 $self->_set_cooldown( $repo, $karr );
1294 $self->_agents->record_failure( $agent->{name}, $result->{error} ) if $agent;
1295 } else {
1296 $self->_clear_cooldown( $repo );
1297 $self->_state_del( $repo, 'last_error' );
1298 if ( $agent && $self->_agents->record_success( $agent->{name} ) ) {
1299 $self->_say_verbose("agent '$agent->{name}' works again");
1300 }
1301 }
1302  
1303 # Update state
1304 my %state = (
1305 hash => $self->_ref_hash( $repo ) // '',
1306 last_run => localtime->datetime,
1307 last_exit => $result->{exit} // 0,
1308 );
1309  
1310 # The last run's own report, where it made one (#187): how it ended, how many
1311 # turns it took, how long it ran, what it cost. It is dropped again by a run
1312 # that reported nothing, for the same reason last_error is (#160): a key that
1313 # is still there describes the last run, and one describing a run three ticks
1314 # ago is a contradiction nobody reading .karr.state can resolve.
1315 if ( $result->{report} ) {
1316 $state{last_result} = $result->{report};
1317 }
1318 else {
1319 $self->_state_del( $repo, 'last_result' );
1320 }
1321  
1322 $self->_state_set( $repo, %state );
1323  
1324 return $result;
1325 }
1326  
1327 # ---------------------------------------------------------------------------
1328 # The domain hook (#193)
1329 # ---------------------------------------------------------------------------
1330  
1331 # What to run when this board has drained, or undef when nothing is configured.
1332 # .karr first, then the config file, like every other key here: a fleet can
1333 # hang one gate on every board it drains, and a board can say something else --
1334 # including `on_drained: ""`, which is how one board opts out of a fleet-wide
1335 # one.
1336 sub _on_drained_command {
1337 my ( $self, $karr ) = @_;
1338 my $cmd = exists $karr->{on_drained}
1339 ? $karr->{on_drained}
1340 : $self->_config_data->{on_drained};
1341 return undef unless defined $cmd && length $cmd;
1342 return $cmd;
1343 }
1344  
1345 # One resolved number for one of the hook's two settings, .karr before config
1346 # before the built-in default.
1347 sub _on_drained_setting {
1348 my ( $self, $karr, $key, $default ) = @_;
1349 return $karr->{$key} // $self->_config_data->{$key} // $default;
1350 }
1351  
1352 # Run the hook, if the board drained and if it is allowed to run at all.
1353 #
1354 # "The board drained" is the observable fact and not an outcome name: no
1355 # actionable task is left on it. The outcome cannot answer this -- a drain that
1356 # empties a board ends on `progress`, because progress is what the last
1357 # iteration made, and `idle` is a run that did nothing on a board that was
1358 # already quiet. Asking the board is also the only question that stays true
1359 # across the run modes: `mode: ticket` does one card and returns, and whether
1360 # that leaves the board empty is not something the mode knows.
1361 #
1362 # karr does not look at what the hook is or what it did. In the fleet this
1363 # design came from it is a release gate that builds a distribution, installs
1364 # it, tests every dependent against it and raises version requirements -- none
1365 # of which belongs in a kanban tool, and all of which would arrive here as
1366 # rules about what the exit code means. So the exit code is written down and
1367 # interpreted by nobody: a hook that fails does not park the board, does not
1368 # mark the board's agent failing, and does not become the run's last_error. It
1369 # is not a run of the agent and is never classified as one.
1370 sub _run_on_drained {
1371 my ( $self, $repo, $karr, $result ) = @_;
1372 my $cmd = $self->_on_drained_command( $karr ) or return;
1373  
1374 # A run that broke tells us nothing about the board. A rate-limited or
1375 # unauthenticated agent leaves a board looking exactly like one it worked
1376 # through, and the cooldown that is about to be set says foundation does not
1377 # believe this run -- so neither does the hook.
1378 my $outcome = $result->{outcome} // '';
1379 return if $outcome eq 'common-error' || $outcome eq 'error';
1380 return if $self->_has_actionable_tasks( $repo );
1381  
1382 my $hash = $self->_ref_hash( $repo ) // '';
1383 my $rounds = $self->_state_get( $repo, 'on_drained_rounds' ) // 0;
1384 my $max = $self->_on_drained_setting( $karr, 'on_drained_max_rounds', 3 );
1385  
1386 # Two guards, and between them the answer to "what stops this being a loop".
1387 # An empty board is not the same as finished work: the hook may fail and file
1388 # tickets, at which point the board is no longer drained, the next tick
1389 # works them, the board drains again and the hook is asked again. That cycle
1390 # is the point -- a gate that files what it found and is re-run once it is
1391 # fixed is exactly what it is for -- so neither guard tries to forbid it.
1392 # What they bound is the two ways it stops being that:
1393 #
1394 # 1. The same board twice. Without this, a repository nobody touches runs
1395 # a release gate on every cron tick for ever, because a drained board
1396 # stays drained. The hook has already had its say about this exact
1397 # state; it is asked again when the state changes.
1398 #
1399 # 2. A chain that never settles. The hook files a ticket, the agent works
1400 # it (or fails it into an auto-block), the board drains, the hook files
1401 # another. Every round changes the board, so guard 1 is no help; the
1402 # board moves for real each time, so nothing else notices either.
1403 # Counting the consecutive rounds in which the hook itself put work back
1404 # is the only thing foundation can observe about it, and it is enough:
1405 # a run that leaves the board alone -- the gate that finally passed --
1406 # clears the count, and a cap stops the ones that never do.
1407 #
1408 # --force overrides both. They are statements about board state, which is
1409 # what --force is documented to override, and unlike the cooldown and the
1410 # agent availability the cap is not time-bounded and does not end by itself,
1411 # so it needs a way out and the operator is it.
1412 unless ( $self->force ) {
1413 # `defined`, not a `// ''` default: a repository whose refs/karr/* cannot
1414 # be fingerprinted at all -- not a karr board, or not a git repository --
1415 # has a hash of '', and defaulting the unset state key to '' would make
1416 # its first drain look like a repeat and silence the hook there for good.
1417 my $last = $self->_state_get( $repo, 'on_drained_hash' );
1418 if ( defined $last && $hash eq $last ) {
1419 $self->_say_verbose(
1420 "skip on_drained in $repo -- the board has not moved since the last one" );
1421 return;
1422 }
1423 if ( $max > 0 && $rounds >= $max ) {
1424 $self->_append_log( $repo, "ON-DRAINED suppressed -- $rounds consecutive "
1425 . "run(s) put work back on the board without settling "
1426 . "(on_drained_max_rounds: $max); --force runs it again" );
1427 return;
1428 }
1429 }
1430  
1431 my ( $exit ) = $self->_run_command( $repo, $karr, $cmd, undef, undef,
1432 role => 'hook',
1433 max_runtime => $self->_on_drained_setting( $karr, 'on_drained_max_runtime', 1800 ),
1434 );
1435  
1436 # Did it put work back? Asked of the board and not of the hook: the hook is
1437 # not obliged to say, and karr is not entitled to know.
1438 my $made_work = ( ( $self->_ref_hash( $repo ) // '' ) ne $hash ) ? 1 : 0;
1439 $self->_append_log( $repo, "ON-DRAINED exit=$exit"
1440 . ( $made_work ? " -- the board moved, so it is no longer drained" : '' ) );
1441  
1442 # on_drained_hash is the state that *triggered* the run, not the one the run
1443 # left behind: the invariant is "the hook is not asked twice about the same
1444 # board", and a hook that files a ticket and has it reverted is being asked
1445 # about a board it has already answered for.
1446 $self->_state_set( $repo,
1447 on_drained_hash => $hash,
1448 on_drained_rounds => ( $made_work ? $rounds + 1 : 0 ),
1449 last_on_drained => {
1450 at => localtime->datetime,
1451 exit => $exit,
1452 made_work => $made_work,
1453 },
1454 );
1455 return;
1456 }
1457  
1458 # ---------------------------------------------------------------------------
1459 # Sync
1460 # ---------------------------------------------------------------------------
1461  
1462 sub _sync_pull {
1463 my ( $self, $repo ) = @_;
1464 $self->_say_verbose("sync --pull $repo");
1465 return if $self->dry_run;
1466 my $git = App::karr::Git->new( dir => "$repo" );
1467 return unless $git->is_repo;
1468 $git->pull;
1469 }
1470  
1471 # The fleet's own namespace, refs/karr-foundation/*, from the hub repository
1472 # (#190). It is a separate call from _sync_pull above because it is a separate
1473 # thing: _sync_pull brings one board up to date on its way into that board's
1474 # drain, this brings the shared plan up to date once, before anything reads it.
1475 #
1476 # It runs before the concurrency limits are resolved, which is the only reader
1477 # there is today: the chain header's `limits:` block. A tick that went on to
1478 # execute chain steps would have to push this namespace back afterwards, with
1479 # the step state and the run log in it, or two machines would run the same
1480 # step -- this one writes nothing there, so there is nothing to push.
1481 #
1482 # A failed pull is a warning and not a refusal. What is lost is the newest
1483 # chain header, and the fallback is this machine's own ceiling, which is the
1484 # safe direction: the local limit is the one that protects the local CPU.
1485 sub _sync_pull_foundation {
1486 my ( $self ) = @_;
1487 my $store = $self->_chain_store or return;
1488 return if $self->dry_run;
1489 $self->_say_verbose('sync --pull refs/karr-foundation/*');
1490 try {
1491 $store->git->pull_foundation;
1492 } catch {
1493 warn 'karr-foundation: pull of refs/karr-foundation/ failed: '
1494 . clean_error($_) . "\n";
1495 };
1496 return;
1497 }
1498  
1499 # ---------------------------------------------------------------------------
1500 # Ref hash (detect board changes)
1501 # ---------------------------------------------------------------------------
1502  
1503 sub _ref_hash {
1504 my ( $self, $repo ) = @_;
1505 my $git = App::karr::Git->new( dir => "$repo" );
1506 return undef unless $git->is_repo;
1507 my $oids = $git->ref_oids('refs/karr/') or return undef;
1508 # Deterministic fingerprint of refs/karr/* (ref name + target OID).
1509 my $out = join '', map { "$_ $oids->{$_}\n" } sort keys %$oids;
1510 return md5_hex( $out );
1511 }
1512  
1513 # ---------------------------------------------------------------------------
1514 # Board-level disable flag (refs/karr/config: foundation.enabled)
1515 # ---------------------------------------------------------------------------
1516  
1517 # The board's own opt-out, stored in karr state rather than in the local .karr
1518 # file so it syncs with the board and every foundation instance on every machine
1519 # honours it. Returns { reason => $text_or_undef } when the board is disabled
1520 # and undef when it is enabled (the default for a board that never set it).
1521 sub _board_disabled {
1522 my ( $self, $repo ) = @_;
1523 my $git = App::karr::Git->new( dir => "$repo" );
1524 return undef unless $git->is_repo;
1525 my $store = App::karr::BoardStore->new( git => $git );
1526 return undef if $store->foundation_enabled;
1527 return { reason => $store->foundation_reason };
1528 }
1529  
1530 # Skip predicate used at the two checkpoints in _process_repo. True (and a
1531 # verbose note) when the board is disabled.
1532 sub _skip_disabled {
1533 my ( $self, $repo ) = @_;
1534 my $off = $self->_board_disabled( $repo ) or return 0;
1535 my $reason = $off->{reason};
1536 $self->_say_verbose(
1537 "skip $repo -- board disabled" . ( defined $reason ? ": $reason" : '' ) );
1538 return 1;
1539 }
1540  
1541 # ---------------------------------------------------------------------------
1542 # Task state / actionability
1543 # ---------------------------------------------------------------------------
1544  
1545 # A task is actionable when there is still work in it: not terminal on its
1546 # board, not held back in backlog, and not blocked. Terminal is the snapshot's
1547 # own verdict, taken from the board's configured statuses when _task_states
1548 # read it (its final status plus `archived`, #67) -- a board whose last column
1549 # is `shipped` is drained when everything on it is shipped, and has no `done`
1550 # to wait for (#305). Held back is the board's verdict the same way (k306): a
1551 # backlog card waits for someone to promote it, not for an agent, so a board
1552 # with nothing but backlog left is drained.
1553 #
1554 # This is not `karr pick` eligibility, and deliberately does not ask the claim:
1555 # the drain's own agent claims the card it works on, and that card has to stay
1556 # actionable for the drain to keep going and for _stuck_tasks to see it stall.
1557 sub _is_actionable {
1558 my ( $self, $st ) = @_;
1559 return 0 unless $st;
1560 return 0 if $st->{blocked};
1561 return 0 if $st->{terminal};
1562 return 0 if $st->{held_back};
1563 return 1;
1564 }
1565  
1566 # Snapshot every task as
1567 # id => { status, claimed_by, updated, blocked, terminal, held_back }.
1568 sub _task_states {
1569 my ( $self, $repo ) = @_;
1570 my $git = App::karr::Git->new( dir => "$repo" );
1571 return () unless $git->is_repo;
1572 my $store = App::karr::BoardStore->new( git => $git );
1573 my %states;
1574 for my $t ( $store->load_tasks ) {
1575 next unless $t;
1576 $states{ $t->id } = {
1577 status => $t->status,
1578 claimed_by => ( $t->has_claimed_by ? $t->claimed_by : undef ),
1579 updated => $t->updated,
1580 blocked => ( $t->has_blocked ? 1 : 0 ),
1581 terminal => ( $store->is_terminal_status( $t->status ) ? 1 : 0 ),
1582 held_back => ( $store->is_held_back_status( $t->status ) ? 1 : 0 ),
1583 };
1584 }
1585 return %states;
1586 }
1587  
1588 sub _has_actionable_tasks {
1589 my ( $self, $repo ) = @_;
1590 my %states = $self->_task_states( $repo );
1591 for my $id ( keys %states ) {
1592 return 1 if $self->_is_actionable( $states{$id} );
1593 }
1594 return 0;
1595 }
1596  
1597 # ---------------------------------------------------------------------------
1598 # Agent engagement (who this run's agent is, and what it touched)
1599 # ---------------------------------------------------------------------------
1600  
1601 # The activity log of the identity foundation runs its agent under. The Runner
1602 # exports KARR_ROLE=agent to the command, so every nested `karr` write during
1603 # the run lands in refs/karr/log/agent/<git-email> — the same identity this
1604 # builds, since the agent runs in this repo with this repo's git config. Any
1605 # other actor on the board (a human, another machine's agent) writes elsewhere.
1606 sub _agent_log_entries {
1607 my ( $self, $repo ) = @_;
1608 my $git = App::karr::Git->new( dir => "$repo" );
1609 return () unless $git->is_repo;
1610 my $log = App::karr::ActivityLog->new( git => $git, role => 'agent' );
1611 return try { $log->entries } catch { () };
1612 }
1613  
1614 # An engagement record for one drain: the log entries already present when the
1615 # drain started (so only what this drain adds counts), the task ids this run's
1616 # agent has written to, and the claim names it wrote them under.
1617 sub _new_engagement {
1618 my ( $self, $repo ) = @_;
1619 my @seen = $self->_agent_log_entries( $repo );
1620 return { seen => scalar @seen, ids => {}, claims => {} };
1621 }
1622  
1623 # Fold the entries the last command added into the record. Nothing else is
1624 # evidence of engagement: a task that never shows up here was never touched by
1625 # this run's agent, whatever its status or claim says.
1626 sub _note_engagement {
1627 my ( $self, $repo, $eng ) = @_;
1628 my @entries = $self->_agent_log_entries( $repo );
1629 return $eng if @entries <= $eng->{seen};
1630 for my $entry ( @entries[ $eng->{seen} .. $#entries ] ) {
1631 my $id = $entry->{task_id};
1632 $eng->{ids}{ $id + 0 } = 1 if defined $id && $id =~ /\A[0-9]+\z/;
1633 my $who = $entry->{agent};
1634 $eng->{claims}{$who} = 1 if defined $who && length $who;
1635 }
1636 $eng->{seen} = scalar @entries;
1637 return $eng;
1638 }
1639  
1640 # True when the card is the agent's to penalize: unclaimed, or held under a
1641 # name this run's agent itself wrote with. A claim belonging to anybody else —
1642 # a human, another machine's agent, or this agent's own abandoned claim from an
1643 # earlier run — is never ours to auto-block.
1644 sub _agent_holds {
1645 my ( $self, $state, $claims ) = @_;
1646 my $owner = $state->{claimed_by};
1647 return 1 unless defined $owner && length $owner;
1648 return ( $claims // {} )->{$owner} ? 1 : 0;
1649 }
1650  
1651 # Tasks this run's agent engaged but did not move — still actionable, written
1652 # to by the agent during this drain, held by nobody but the agent, and
1653 # byte-identical before/after the last command. These are the only tasks that
1654 # count toward an auto-block.
1655 #
1656 # Engagement is proven, never assumed: without an entry of the agent's own in
1657 # $eng, foundation has no evidence it ever attempted the task, and an
1658 # auto-block would be a destructive write to somebody else's card carrying a
1659 # reason that is factually wrong (#158). So an engagement it cannot establish —
1660 # an agent that does not write through karr, an unreadable log, a stale claim
1661 # nobody touched this run — yields no stuck tasks and no auto-block at all.
1662 # Failing to block a genuinely stuck card only leaves the drain to end on its
1663 # iteration cap; blocking a stranger's card takes their work out of the
1664 # actionable set behind their back.
1665 sub _stuck_tasks {
1666 my ( $self, $before, $after, $eng ) = @_;
1667 my $ids = ( $eng // {} )->{ids} // {};
1668 my $claims = ( $eng // {} )->{claims} // {};
1669 my @stuck;
1670 for my $id ( sort { $a <=> $b } keys %$after ) {
1671 my $a = $after->{$id};
1672 next unless $self->_is_actionable( $a );
1673 next unless $ids->{$id}; # the agent never touched it
1674 next unless $self->_agent_holds( $a, $claims ); # somebody else holds it
1675 next unless defined $a->{claimed_by} || ( $a->{status} // '' ) eq 'in-progress';
1676 my $b = $before->{$id} or next; # newly created this run — give it grace
1677 next if ( $b->{status} // '' ) ne ( $a->{status} // '' );
1678 next if ( $b->{updated} // '' ) ne ( $a->{updated} // '' );
1679 push @stuck, $id;
1680 }
1681 return @stuck;
1682 }
1683  
1684 # ---------------------------------------------------------------------------
1685 # Drain loop
1686 # ---------------------------------------------------------------------------
1687  
1688 # Run the agent repeatedly until the board has no actionable tasks left,
1689 # auto-blocking tasks the agent keeps failing on. Returns
1690 # { outcome => progress|stall|idle|common-error|error, exit => N, ticket => ID,
1691 # report => {...}, error => STR } (ticket is undef outside mode: ticket;
1692 # error is set only on a common-error outcome).
1693 # $agent is the named agent definition behind $cmd, or undef.
1694 #
1695 # %opt is the chain executor's (#202): `ticket` is the card the plan named --
1696 # which makes this a ticket-mode run whatever the .karr file says, because a
1697 # step that names a card and a repo configured to drain cannot both be obeyed
1698 # and the plan is the more specific statement -- and `timeout` is the step's own
1699 # budget, which beats the board's default for the same reason.
1700 sub _drain_repo {
1701 my ( $self, $repo, $karr, $cmd, $agent, %opt ) = @_;
1702 my $max_runtime = $opt{timeout} // $karr->{max_runtime} // 1800;
1703 my $max_attempts = $karr->{max_attempts} // 2;
1704 my $max_iter = $karr->{max_iterations} // 50;
1705 my $mode = defined $opt{ticket} ? 'ticket' : $self->_run_mode( $karr );
1706 my $drain = $mode eq 'drain' ? 1 : 0;
1707 my $patterns = $self->_error_patterns( $karr );
1708  
1709 # Use the resolved command, not $karr->{command}
1710 $cmd //= $karr->{command};
1711  
1712 # Ticket mode names the card before the agent starts, and the run is about
1713 # that card and nothing else. No card, no run: "run exactly one ticket" has
1714 # nothing to say when the board has no ticket to give, and an agent started
1715 # anyway would go looking for work of its own, which is the mode this one
1716 # exists to replace. --force and on_idle: always-run force the *check*, not a
1717 # run without a card.
1718 my $ticket;
1719 if ( $mode eq 'ticket' ) {
1720 $ticket = defined $opt{ticket} ? $opt{ticket} : $self->_select_ticket( $repo );
1721 unless ( defined $ticket ) {
1722 $self->_append_log( $repo, "TICKET none assignable -- no agent run" );
1723 return { outcome => 'idle', exit => 0, ticket => undef };
1724 }
1725 $self->_append_log( $repo, "TICKET task#$ticket" );
1726 }
1727  
1728 my $loop_start = time;
1729 my $last_exit = 0;
1730 my $outcome = 'idle';
1731 my $first = 1;
1732 my $iter = 0;
1733  
1734 # The last run's own report, summarised (Runner::_result_summary), or undef
1735 # while no run has made one. It survives the loop so a drain hands back what
1736 # its final iteration reported.
1737 my $last_report;
1738  
1739 # The common error that ended the drain, where one did. It leaves the loop
1740 # because the caller needs it for two things now: .karr.state's last_error,
1741 # which the drain writes itself, and the named agent's availability record,
1742 # which is the caller's to write.
1743 my $error;
1744  
1745 # What this run's agent engages, accumulated across the whole drain: the
1746 # iteration that claims a task is the one that moves the board, so the stall
1747 # only becomes visible one or more iterations later.
1748 my $eng = $self->_new_engagement( $repo );
1749  
1750 while ( 1 ) {
1751 my %before = $self->_task_states( $repo );
1752 my @actionable = grep { $self->_is_actionable( $before{$_} ) } keys %before;
1753  
1754 # Once we have run at least once, stop when the board is drained, the
1755 # wall-clock budget is spent, or we hit the hard iteration cap. The
1756 # wall-clock check is skipped when max_runtime is 0: that value disables
1757 # the per-run timeout entirely (documented, Runner.pm), and the drain's
1758 # budget must not silently inherit the same "no limit" sentinel as a
1759 # hard zero — `>= 0` is always true after the first iteration and would
1760 # turn drain: true into a single run (#165). With max_runtime: 0 the
1761 # drain runs until the board is drained or the iteration cap.
1762 last if !$first && !@actionable;
1763 last if !$first && $max_runtime > 0 && ( time - $loop_start ) >= $max_runtime;
1764 last if $iter >= $max_iter;
1765  
1766 my $hash_before = $self->_ref_hash( $repo ) // '';
1767 my ( $exit, $output ) = $self->_run_command( $repo, $karr, $cmd, $ticket, $agent,
1768 ( defined $opt{timeout} ? ( max_runtime => $opt{timeout} ) : () ) );
1769 $last_exit = $exit;
1770 $first = 0;
1771 $iter++;
1772  
1773 # --dry-run started nothing: the runner logged the START it would have made
1774 # and DRY-RUN (skipped), and came back without a run. There is no run to
1775 # judge, so nothing below may judge one -- ticket mode called the unmoved
1776 # card a STALL for an agent that never started (#314). Idle, like a run
1777 # that did nothing, and no second would-be START: nothing a skipped run
1778 # "did" can change what the next iteration would see.
1779 last if $self->dry_run;
1780  
1781 my $hash_after = $self->_ref_hash( $repo ) // '';
1782 my $progressed = ( $hash_before ne $hash_after ) ? 1 : 0;
1783  
1784 # What the run said about itself, where it said anything: a claude-code
1785 # result object at the end of its output (Runner::_run_result explains how
1786 # foundation finds one and why it looks there and nowhere else). This is
1787 # the classification the text scan below has always been a stand-in for
1788 # (#187) — error flag, error kind, turns, duration, cost, stated by the
1789 # run rather than inferred from its prose.
1790 my ( $ended, $rerr );
1791 my $report = $self->_run_result( $output );
1792 if ( $report ) {
1793 ( $rerr, $ended ) = $self->_result_error( $report );
1794 $last_report = $self->_result_summary( $report, $ended );
1795 $self->_append_log( $repo, $self->_result_line( $report, $ended ) );
1796 }
1797  
1798 # Common error we can observe (bad exit, timeout, a report that says so, or
1799 # a known output pattern): don't penalize any task — leave the board
1800 # untouched and back off. What the run *did* is asked before what it
1801 # *printed* (#160): a run that exited 0 and moved the board did work,
1802 # whatever text went past on the way, and re-reading its own transcript is
1803 # the one way to lose that work — the drain aborted, the progress was
1804 # credited to nobody, and the cooldown climbed on every following run
1805 # because the board still said the same words. So the output is evidence
1806 # only where there is nothing else: a run that produced no board movement
1807 # at all. The genuine case the scan exists for looks exactly like that,
1808 # because an agent that hit a rate limit or a dead key could not move
1809 # anything.
1810 #
1811 # A report is not in that ordering at all, and this is the one place to be
1812 # careful not to invert it. The guard above protects the run from an
1813 # *inference*: a word search over megabytes the agent printed, which cannot
1814 # tell the agent's report from the board's own contents. A field in the
1815 # agent's own result object is not an inference, so it ranks with the exit
1816 # code rather than with the scan — and where there is a report, the scan
1817 # does not run at all. That is the whole point: an agent that prints a
1818 # backlog full of 503s and then reports success is a success.
1819 my $err;
1820 if ( $report ) {
1821 $err = $rerr;
1822 # A non-zero exit the report does not account for is still an error: the
1823 # report is claude's, the exit code may be the wrapper's, and a report of
1824 # success says nothing about a pipeline that failed after it (or about
1825 # the 128+SIGTERM the runner synthesizes for a run it had to kill). A
1826 # report that *does* carry an error flag has already accounted for it,
1827 # which is what lets a spent turn budget — claude exits 1 on
1828 # error_max_turns — stop parking the board for an hour.
1829 $err //= "exit=$exit" if $exit != 0 && !$report->{is_error};
1830 }
1831 elsif ( $exit != 0 ) {
1832 $err = "exit=$exit"; # or -1, the timeout — a hard signal, no scan
1833 }
1834 else {
1835 my $seen = $self->_match_error( $output, $patterns );
1836 if ( defined $seen && $progressed ) {
1837 # Worth saying once: an agent that reports a rate limit and still gets
1838 # a card moved is on its last legs, and the operator should hear it
1839 # from the log rather than from the next run's cooldown.
1840 $self->_append_log( $repo,
1841 "NOTE '$seen' in output, but the board moved -- not treated as an error" );
1842 }
1843 else {
1844 $err = $seen;
1845 }
1846 }
1847  
1848 if ( defined $err ) {
1849 # An exit-0 run that is thrown away is the surprising one; .karr.state
1850 # would otherwise carry last_exit: 0 next to last_error with nothing
1851 # anywhere saying why the run did not count.
1852 my $why = $exit == 0 ? " -- agent exited 0, run discarded" : '';
1853 $self->_append_log( $repo, "COMMON-ERROR $err$why" );
1854 $self->_state_set( $repo, last_error => $err );
1855 $outcome = 'common-error';
1856 $error = $err;
1857 last;
1858 }
1859  
1860 my %after = $self->_task_states( $repo );
1861 $self->_note_engagement( $repo, $eng );
1862  
1863 my @stuck;
1864 if ( defined $ticket ) {
1865 # A ticket-mode run is judged by its own card, not by the board hash: an
1866 # agent that ignored its assignment and moved something else did move the
1867 # board, and calling that progress would tell the coordinator its ticket
1868 # was worked when it was not.
1869 if ( $self->_ticket_moved( \%before, \%after, $ticket ) ) {
1870 $outcome = 'progress';
1871 }
1872 else {
1873 $outcome = 'stall';
1874 # Which stall it was. "The agent reports it cannot proceed" and "the
1875 # agent did nothing" both end as a card that did not move, and until a
1876 # run reported for itself there was nothing to tell them apart with
1877 # (#187). Ticket mode is the caller that wants the difference most: it
1878 # is the one place foundation already knows what the run was supposed
1879 # to be about, so the only thing missing was what the agent made of it.
1880 $self->_append_log( $repo,
1881 "STALL task#$ticket -- " . $self->_stall_reason( $report, $ended ) );
1882 # foundation assigned this card, so it needs no activity-log evidence
1883 # that the agent engaged it -- the assignment is the evidence, and the
1884 # counter it bumps is foundation's own .karr.state. The auto-block a
1885 # few lines below is the destructive half, and that one keeps #158's
1886 # ownership guard: a card somebody else took during the run is never
1887 # blocked on our say-so.
1888 @stuck = ( $ticket )
1889 if $self->_agent_holds( $after{$ticket}, $eng->{claims} );
1890 }
1891 }
1892 else {
1893 $outcome = 'progress' if $progressed;
1894 @stuck = $self->_stuck_tasks( \%before, \%after, $eng );
1895 }
1896  
1897 # Reset the attempt counter for any task that is no longer stuck
1898 # (advanced, blocked, or gone), then bump/auto-block the stuck ones.
1899 my %is_stuck = map { $_ => 1 } @stuck;
1900 my $attempts = $self->_state_get( $repo, 'attempts' ) // {};
1901 $self->_reset_attempts( $repo, $_ ) for grep { !$is_stuck{$_} } keys %$attempts;
1902  
1903 for my $id ( @stuck ) {
1904 my $n = $self->_bump_attempts( $repo, $id );
1905 next if $n < $max_attempts;
1906 $self->_autoblock_task( $repo, $id,
1907 "auto-block: no progress after $n attempts (foundation)",
1908 $eng->{claims} );
1909 $self->_reset_attempts( $repo, $id );
1910 }
1911  
1912 # Agent did nothing useful and grabbed nothing — stop, nothing to attribute.
1913 # Not in ticket mode: there the run has already been judged against its own
1914 # card, and a stall foundation may not penalize (somebody else holds the
1915 # card now) is still a stall, not a run that found nothing to do.
1916 if ( !defined $ticket && !$progressed && !@stuck ) {
1917 $outcome = 'idle';
1918 last;
1919 }
1920  
1921 last unless $drain; # single / ticket mode → one run and return
1922 }
1923  
1924 return {
1925 outcome => $outcome,
1926 exit => $last_exit,
1927 ticket => $ticket,
1928 report => $last_report,
1929 error => $error,
1930 };
1931 }
1932  
1933 # A ticket-mode stall, said in the terms a coordinator asks in. Without a
1934 # report there is nothing to say and it says so, rather than guessing: an agent
1935 # that produces no structured result is exactly the case foundation has no
1936 # information about, and inventing a reason for it is how the text scan got
1937 # into trouble in the first place (#160).
1938 sub _stall_reason {
1939 my ( $self, $report, $ended ) = @_;
1940 return 'no report from the agent' unless defined $ended;
1941 return 'the agent ran out of turns' if $ended eq 'max turns';
1942 return "the agent ended with $ended" if $ended ne 'success';
1943 return 'the agent reported success but the card did not move';
1944 }
1945  
1946 # Did the assigned card come out of the run different from how it went in?
1947 # Gone, no longer actionable (done, blocked), or its blob rewritten — status or
1948 # updated, the same two fields _stuck_tasks compares, so a claim, a status
1949 # change and an appended note all count. Everything else is a run that did not
1950 # touch its own ticket.
1951 sub _ticket_moved {
1952 my ( $self, $before, $after, $id ) = @_;
1953 my $a = $after->{$id} or return 1;
1954 return 1 unless $self->_is_actionable( $a );
1955 my $b = $before->{$id} or return 1;
1956 return 1 if ( $b->{status} // '' ) ne ( $a->{status} // '' );
1957 return 1 if ( $b->{updated} // '' ) ne ( $a->{updated} // '' );
1958 return 0;
1959 }
1960  
1961 # ---------------------------------------------------------------------------
1962 # Run mode / ticket selection
1963 # ---------------------------------------------------------------------------
1964  
1965 # What a run of this repo is: 'drain' (loop until the board stops moving, the
1966 # historical default), 'single' (exactly one agent run, agent picks its own
1967 # work) or 'ticket' (exactly one agent run, about a card foundation names).
1968 #
1969 # 'drain: true|false' said two thirds of this before there was a third answer,
1970 # and it stays honoured rather than being deprecated into a warning: it is
1971 # written in .karr files this foundation does not own. Two keys that both mean
1972 # "one run" would be the trap, so they are one key with an alias, not two
1973 # switches: 'mode' is asked first and 'drain' only answers when 'mode' is
1974 # absent. Per-repo before global, as everywhere else here — a repo that says
1975 # 'drain: false' means it against a config-wide 'mode: ticket', because the
1976 # .karr file is the more specific statement.
1977 sub _run_mode {
1978 my ( $self, $karr ) = @_;
1979 my $mode = $karr->{mode};
1980 unless ( defined $mode ) {
1981 return $karr->{drain} ? 'drain' : 'single' if exists $karr->{drain};
1982 $mode = $self->_config_data->{mode};
1983 }
1984 return 'drain' unless defined $mode;
1985 # A typo here is not a small mistake: 'ticekt' silently draining a board is
1986 # the opposite of what was asked for, on every tick, quietly. The caller
1987 # (_process_repo) turns this into a warning and skips the repo.
1988 user_error("Unknown mode '$mode' (expected: drain, single or ticket)")
1989 unless $mode eq 'drain' || $mode eq 'single' || $mode eq 'ticket';
1990 return $mode;
1991 }
1992  
1993 # The card a ticket-mode run is about, or undef when the board has none to
1994 # give. Selection is a read: nothing is claimed and nothing is locked here —
1995 # see App::karr::Foundation::Picker for why the claim stays the agent's.
1996 sub _select_ticket {
1997 my ( $self, $repo ) = @_;
1998 my $git = App::karr::Git->new( dir => "$repo" );
1999 return undef unless $git->is_repo;
2000 my $store = App::karr::BoardStore->new( git => $git );
2001 return App::karr::Foundation::Picker->new( store => $store )->next_ticket;
2002 }
2003  
2004 # ---------------------------------------------------------------------------
2005 # Auto-block (in-process via BoardStore, no karr CLI)
2006 # ---------------------------------------------------------------------------
2007  
2008 # $claims is the set of claim names this run's agent wrote under (see
2009 # _note_engagement). The ownership test is repeated here, at the write itself,
2010 # rather than trusted from _stuck_tasks: this is the one place that mutates
2011 # somebody's card and pushes it, the board may have changed since the snapshot
2012 # the caller decided on, and any future caller inherits the guarantee instead
2013 # of having to remember it (#158).
2014 sub _autoblock_task {
2015 my ( $self, $repo, $id, $reason, $claims ) = @_;
2016 return if $self->dry_run;
2017 my $git = App::karr::Git->new( dir => "$repo" );
2018 return unless $git->is_repo;
2019 my $store = App::karr::BoardStore->new( git => $git );
2020 my $task = $store->find_task( $id ) or return;
2021 unless ( $self->_agent_holds(
2022 { claimed_by => ( $task->has_claimed_by ? $task->claimed_by : undef ) },
2023 $claims ) ) {
2024 $self->_append_log( $repo,
2025 "AUTOBLOCK-SKIP task#$id: claimed by " . $task->claimed_by );
2026 return 0;
2027 }
2028 $task->block( $reason );
2029 $store->save_task( $task );
2030 $git->push; # best-effort propagate to remote
2031 $self->_append_log( $repo, "AUTOBLOCK task#$id: $reason" );
2032 return 1;
2033 }
2034  
2035 # ---------------------------------------------------------------------------
2036 # Log file
2037 # ---------------------------------------------------------------------------
2038  
2039 sub _append_log {
2040 my ( $self, $repo, $msg ) = @_;
2041 my $ts = localtime->strftime('%Y-%m-%dT%H:%M:%S');
2042 my $line = "[$ts] $$: $msg\n";
2043 print $line if $self->verbose;
2044 return if $self->dry_run;
2045 $repo->child('.karr.log')->append_utf8( $line );
2046 }
2047  
2048 sub _say_verbose {
2049 my ( $self, $msg ) = @_;
2050 print "$msg\n" if $self->verbose;
2051 }
2052  
2053 # ---------------------------------------------------------------------------
2054 # .karr file
2055 # ---------------------------------------------------------------------------
2056  
2057 sub _load_karr {
2058 my ( $self, $repo ) = @_;
2059 my $karr_file = $repo->child('.karr');
2060 return {} unless $karr_file->exists;
2061 my $data = try {
2062 YAML::XS::LoadFile("$karr_file");
2063 } catch {
2064 warn "karr-foundation: cannot parse $karr_file: $_\n";
2065 {};
2066 };
2067 return ref $data eq 'HASH' ? $data : {};
2068 }
2069  
2070 # ---------------------------------------------------------------------------
2071 # Agent command resolution
2072 # ---------------------------------------------------------------------------
2073  
2074 # What this repo runs, as ( $command, $invocation ). $command is the shell
2075 # string, or undef when no agent is configured at all. $invocation is set only
2076 # where the command came from a B<named> agent definition (see
2077 # L<App::karr::Foundation::Agents>) and carries its name, kind and live-output
2078 # rendering; it is undef for every other source, which is what keeps a board
2079 # that knows nothing about agent definitions behaving exactly as before -- no
2080 # availability is recorded against it, and nothing is appended to its command.
2081 #
2082 # Priority: CLI --command > config default_command > .karr command >
2083 # .karr agent > the assignment (#210) > config default_agent >
2084 # 'claude: true' shorthand.
2085 #
2086 # The third return value is a reason to WAIT: the assignment routes this board
2087 # and every agent it names is currently failing, or it says WAIT outright. That
2088 # is not "no agent configured" and must not read as one -- the board runs
2089 # nothing this tick and runs again when an agent it is allowed to use comes
2090 # back.
2091 #
2092 # A named agent sits below the literal command strings and above the claude
2093 # shorthand: `command:` is the most specific thing a board can say (it is a
2094 # whole invocation, written out), while `claude: true` is the oldest and least
2095 # specific. A .karr `agent:` beats the config's `default_agent` for the same
2096 # reason every other key here does -- the board is the more specific statement.
2097 sub _resolve_agent {
2098 my ( $self, $repo, $karr ) = @_;
2099 my $cfg = $self->_config_data;
2100  
2101 for my $candidate ( $self->command, $cfg->{default_command}, $karr->{command} ) {
2102 return ( $candidate, undef ) if defined $candidate && length $candidate;
2103 }
2104  
2105 # The assignment (#210), between the board's own `agent:` and the fleet-wide
2106 # `default_agent`. A board that names an agent has said the most specific
2107 # thing there is to say about itself and is not routed; a board that has not
2108 # is exactly what the coordination agent's routing table is for, and that
2109 # table is per repository, so it beats a default that is per fleet.
2110 #
2111 # Three answers, and only the first two are this method's business: an agent
2112 # to run, a reason to wait (returned as the third value -- a board whose
2113 # chain is exhausted or says WAIT runs nothing this tick and is NOT the same
2114 # as a board with no agent configured), or nothing, in which case resolution
2115 # carries on exactly as it did before there was an assignment at all.
2116 my $named = $karr->{agent};
2117 unless ( defined $named && length $named ) {
2118 my $routed = $self->_coordinator->route( $repo );
2119 return ( undef, undef, $routed->{wait} ) if $routed && defined $routed->{wait};
2120 $named = $routed->{agent} if $routed && defined $routed->{agent};
2121 $named //= $cfg->{default_agent};
2122 }
2123 if ( defined $named && length $named ) {
2124 # An unknown name raises: a typo here is not a small mistake. Silently
2125 # falling back to no agent would park the board for good and say nothing,
2126 # which is what `mode:` refuses to do for the same reason. _process_repo
2127 # runs inside run()'s per-repo try, so this warns and skips one board.
2128 my $inv = $self->_agents->invocation( $named );
2129 return ( $inv->{command}, $inv );
2130 }
2131  
2132 my $claude = exists $karr->{claude} ? $karr->{claude} : $cfg->{claude};
2133 return ( $self->_claude_command($karr), undef ) if $claude;
2134  
2135 return ( undef, undef );
2136 }
2137  
2138 # The resolved agent command string, or undef when no agent is configured.
2139 sub _agent_command {
2140 my ( $self, $repo, $karr ) = @_;
2141 my ( $cmd ) = $self->_resolve_agent( $repo, $karr );
2142 return $cmd;
2143 }
2144  
2145 # Synthesize the canonical claude invocation behind 'claude: true'. The $PROMPT
2146 # variable is substituted from $ENV{PROMPT} at run time (see _run_command), so
2147 # users never retype the long flag set. claude_bin / claude_max_turns /
2148 # claude_permission_mode override the defaults (per-repo, then global).
2149 sub _claude_command {
2150 my ( $self, $karr ) = @_;
2151 my $cfg = $self->_config_data;
2152 my $bin = $karr->{claude_bin} // $cfg->{claude_bin} // 'claude';
2153 my $turns = $karr->{claude_max_turns} // $cfg->{claude_max_turns} // 30;
2154 my $perm = $karr->{claude_permission_mode} // $cfg->{claude_permission_mode} // 'bypassPermissions';
2155 return qq{$bin -p "\$PROMPT" --permission-mode $perm --max-turns $turns};
2156 }
2157  
2158 # The agent instruction exposed as $PROMPT. .karr 'prompt' > config
2159 # 'default_prompt' > the built-in default.
2160 #
2161 # With a $ticket the built-in default changes (the ordinary one opens by
2162 # telling the agent to pick its own work) and the assignment sentence is
2163 # appended to whatever prompt was resolved. Appending rather than replacing
2164 # keeps a configured prompt doing its job — it is usually about which skill to
2165 # use and how to report — while the last sentence, which is the one that wins
2166 # with a language model, is the one naming the card. Without this the mode
2167 # would be `drain: false` with extra steps: the agent would never learn which
2168 # ticket it was given.
2169 sub _prompt_for {
2170 my ( $self, $karr, $ticket ) = @_;
2171 my $configured = $karr->{prompt} // $self->_config_data->{default_prompt};
2172 return $configured // $DEFAULT_PROMPT unless defined $ticket;
2173 return ( $configured // $DEFAULT_TICKET_PROMPT ) . "\n\n"
2174 . sprintf( $TICKET_ASSIGNMENT, $ticket );
2175 }
2176  
2177 1;
2178  
2179 __END__
« lib/App/karr/Git.pm ↑ Summary blib/lib/App/karr/Role/CompactOutput.pm »