blib/lib/App/karr/Cmd/Context.pm

filter: Statementstmt 91.6% 22 / 24 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.7% 30 / 32 CC 1 SCAR 0.4
CC
1
Cov
92%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/App/karr/Role/TaskMutation.pm ↑ Summary lib/App/karr/Git.pm »
1 # ABSTRACT: Generate board context summary for embedding
2  
3 package App::karr::Cmd::Context;
4 our $VERSION = '0.602';
5 3 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use MooX::Cmd;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use MooX::Options (
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 usage_string => 'USAGE: karr context [--write-to FILE] [--sections LIST] [--days N] '
9 . '[--activity-limit N] [--json] [--compact]',
10 3 );
11 3 ▶use Path::Tiny ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use App::karr::Error qw( user_error clean_error );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use App::karr::Encoding qw( json_decode );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 3 ▶use Time::Piece;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 0 ▶use App::karr::Role::BoardAccess;
Subroutine BEGIN: called CC=1 SCAR=2.6
16 use App::karr::Role::Output;
17 use App::karr::Role::CompactOutput;
18 use App::karr::Task;
19 use App::karr::Config;
20  
21 with 'App::karr::Role::BoardAccess', 'App::karr::Role::Output',
22 'App::karr::Role::CompactOutput';
23  
24  
25 option write_to => (
26 is => 'ro',
27 format => 's',
28 doc => 'Write context to file (create or update)',
29 );
30  
31 option sections => (
32 is => 'ro',
33 format => 's',
34 doc => 'Comma-separated section filter (in-progress,blocked,overdue,recently-completed,activity)',
35 );
36  
37 option days => (
38 is => 'ro',
39 format => 'i',
40 default => sub { 7 },
41 doc => 'Lookback days for recently-completed (default: 7)',
42 );
43  
44 option activity_limit => (
45 is => 'ro',
46 format => 'i',
47 default => sub { 5 },
48 doc => "Other agents' recent log entries to include in activity (default: 5)",
49 );
50  
51 sub execute {
52 my ($self, $args_ref, $chain_ref) = @_;
53  
54 # --activity-limit is a count, so 0 and negatives are invalid values rather
55 # than requests for a differently sized section -- and here the wrong answer
56 # is worse than usual: the falsy guard in _recent_activity reads 0 as "no
57 # bound at all", so the one option whose whole job is to keep the briefing
58 # short would silently pour the entire log into it, and a negative produced
59 # an empty section and exit 0, indistinguishable from "nobody else acted".
60 # Same rule and same reason as `show --last` (ticket #76, ADR 0002).
61 $self->usage_error(
62 sprintf '--activity-limit must be 1 or greater (got %d)', $self->activity_limit )
63 if $self->activity_limit < 1;
64  
65 # A briefing built from a board that was never read says "0 tasks, nothing
66 # blocked, nothing overdue" -- the most confident possible way to be wrong,
67 # and --write-to would then paste it into AGENTS.md (#135).
68 $self->require_local_board;
69  
70 my $ec = $self->store->effective_config;
71 my @tasks = $self->load_tasks;
72 my @statuses = $self->store->all_status_names;
73  
74 # Determine terminal and first statuses
75 my $first_status = $statuses[0];
76  
77 # Archived, and nothing else. The boundary is kanban-md's IsArchivedStatus
78 # (cmd/context.go filters the list with it), and that is literally
79 # `s == "archived"` -- not "terminal". A finished card is still part of what
80 # the board reports about itself: it counts in the header total and can show
81 # up under recently-completed. Only filed-away work drops out of the briefing
82 # entirely. Excluding every terminal status here instead (as karr did between
83 # 85f6e9f and ticket #229) would drop `done` from the total on the default
84 # board, so @context_tasks stays wide.
85 #
86 # The values below that must NOT see terminal cards test the status
87 # themselves, as kanban-md's computeSummary does for most of them: `active`,
88 # `_is_overdue` and the in-progress section each carry their own
89 # is_terminal_status check -- and `blocked` now joins them (ticket #295).
90 #
91 # `blocked` is a DELIBERATE divergence from kanban-md, not a bug. kanban-md's
92 # computeSummary counts a card as blocked even in a terminal status, and #229
93 # once matched that here so a co-driven shared block held identical numbers.
94 # #295 reverses that call: a card in a terminal status is finished and is not
95 # an active blocker, so it is neither counted nor listed as blocked, the same
96 # rule `karr board`'s footer applies. block_reason is untouched and `karr list
97 # --blocked --status done` still surfaces it. Accepted consequence: the
98 # blocked count in the shared sentinel block (see _render_markdown) can now
99 # differ from the one kanban-md would write for the same board. See
100 # docs/adr/0006-context-diverges-from-kanban-md-on-terminal-blocked-counting.md.
101 my @context_tasks = grep { $_->status ne App::karr::Config->ARCHIVED_STATUS } @tasks;
102  
103 # Build summary
104 my $board_name = $ec->{board}{name} // 'Kanban Board';
105 my $total = scalar @context_tasks;
106 # "Active" is kanban-md's computeSummary rule -- not the first status, not a
107 # terminal one -- so it counts the same span the "In Progress" section renders
108 # below, blocked cards included. See there for why that span is wider than the
109 # heading sounds.
110 my $active = grep { $_->status ne $first_status && !$self->store->is_terminal_status($_->status) } @context_tasks;
111 # Terminal cards excluded (ticket #295): a finished card carrying a stale
112 # blocked flag is not an active blocker. Same is_terminal_status test `active`
113 # above uses, so the two summary numbers agree on what "finished" means.
114 my $blocked = grep { $_->has_blocked && !$self->store->is_terminal_status($_->status) } @context_tasks;
115 my $overdue = $self->_count_overdue(\@context_tasks);
116  
117 # Build sections
118 my %wanted_sections;
119 if ($self->sections) {
120 %wanted_sections = map { $_ => 1 } split /,/, $self->sections;
121 }
122  
123 my @section_data;
124 my @all_sections = qw(in-progress blocked overdue recently-completed activity);
125  
126 for my $sec (@all_sections) {
127 next if $self->sections && !$wanted_sections{$sec};
128 my @items;
129  
130 if ($sec eq 'in-progress') {
131 # Wider than its heading: everything between the first status and the
132 # terminal ones, minus the blocked -- on the default board that is `todo`,
133 # `in-progress` and `review`, not the column of the same name alone. Both
134 # halves are kanban-md's: the three conditions from buildInProgressSection,
135 # the "In Progress" title from its sectionTitle, and computeSummary counts
136 # that same span as "active" in the header above.
137 #
138 # Narrowing the section to the literal `in-progress` column would break the
139 # sentinel interop contract explained in _render_markdown below: karr and
140 # kanban-md maintain one block in a shared host file, so they have to agree
141 # on what goes in it, heading included.
142 @items = map { $self->_task_item($_) }
143 sort { $self->_pri_order($a) <=> $self->_pri_order($b) }
144 grep { $_->status ne $first_status && !$self->store->is_terminal_status($_->status) && !$_->has_blocked }
145 @context_tasks;
146 } elsif ($sec eq 'blocked') {
147 # Terminal cards excluded, matching the header count above (ticket #295):
148 # a finished card is not listed as an active blocker even if its flag is
149 # still set. block_reason stays put; --status done still surfaces it.
150 @items = map { $self->_task_item($_, 'blocked: ' . ($_->has_block_reason ? $_->block_reason : '')) }
151 grep { $_->has_blocked && !$self->store->is_terminal_status($_->status) }
152 @context_tasks;
153 } elsif ($sec eq 'overdue') {
154 my $now = gmtime->strftime('%Y-%m-%d');
155 @items = map { $self->_task_item($_, 'due ' . $_->due) }
156 grep { $self->_is_overdue($_, $now) }
157 @context_tasks;
158 } elsif ($sec eq 'recently-completed') {
159 # Over every task, not @context_tasks. When ticket #99 was written that
160 # list was the non-terminal cards, so intersecting it with the terminal
161 # statuses was empty by construction and this section had never once had
162 # an entry on any board. It now holds everything but the archived (#229),
163 # which makes the two spans equal -- the `ne archived` test below is what
164 # keeps filed-away work out either way, and is why this branch did not
165 # move with that fix. kanban-md's buildRecentlyCompletedSection likewise
166 # scans the whole list it is handed.
167 #
168 # "Recently" is bounded by the completion stamp, as it is there, but to
169 # the day rather than to the second: `completed` is a string here and an
170 # interop card can carry it as a bare `YYYY-MM-DD`, as an RFC3339 stamp
171 # in UTC, or as one with a local offset, and a day-granular cutoff is the
172 # coarsest bound all three compare correctly against.
173 my $cutoff = (gmtime() - ($self->days * 86400))->strftime('%Y-%m-%d');
174 @items = map { $self->_task_item($_, 'completed ' . ($_->completed // '')) }
175 sort { ($b->completed // '') cmp ($a->completed // '') }
176 grep { $self->store->is_terminal_status($_->status)
177 && $_->status ne App::karr::Config->ARCHIVED_STATUS
178 && $_->has_completed && $_->completed ge $cutoff }
179 @tasks;
180 } elsif ($sec eq 'activity') {
181 @items = $self->_recent_activity;
182 }
183  
184 push @section_data, { name => $sec, items => \@items } if @items;
185 }
186  
187 # --write-to is a SIDE EFFECT and the output flags decide stdout; the two
188 # were never in conflict (ticket #260). --write-to does not redirect the
189 # output, it maintains a block delimited by sentinels karr shares with
190 # kanban-md inside a host file. What goes between those sentinels is
191 # Markdown by that interop contract and is not the caller's to choose, so
192 # neither --json nor --compact has anything to say about the FILE -- and
193 # neither is a reason to skip the write.
194 #
195 # Both were getting that wrong from opposite sides. --json answered and
196 # returned before --write-to was read at all: no file, exit 0, and nothing
197 # said -- the option whose only job is to write, accepted and dropped, the
198 # class #225/#226/#254 are about. --compact wrote the file and dropped its
199 # own rendering instead. One rule now covers both.
200 my $stdout_wants_markdown = !( $self->json || $self->compact );
201 my $md =
202 ( $self->write_to || $stdout_wants_markdown )
203 ? $self->_render_markdown($board_name, $total, $active, $blocked, $overdue, \@section_data)
204 : undef;
205  
206 $self->_write_to_file($md) if $self->write_to;
207  
208 if ($self->json) {
209 my $out = {
210 board_name => $board_name,
211 summary => {
212 total_tasks => $total,
213 active => $active,
214 blocked => $blocked,
215 overdue => $overdue,
216 },
217 sections => \@section_data,
218 };
219 $self->print_json($out);
220 return;
221 }
222  
223 # The header numbers alone, keyed the way the --json summary keys them so a
224 # reader does not have to learn two vocabularies for the same four counts.
225 # Below --json and above the Markdown, the place `pick` cuts (#251): the
226 # payload is never reshaped by --compact, the prose is.
227 if ($self->compact) {
228 printf "board_name=%s\n", $board_name;
229 printf "total_tasks=%d\n", $total;
230 printf "active=%d\n", $active;
231 printf "blocked=%d\n", $blocked;
232 printf "overdue=%d\n", $overdue;
233 return;
234 }
235  
236 print $md;
237 }
238  
239 sub _render_markdown {
240 my ($self, $board_name, $total, $active, $blocked, $overdue, $sections) = @_;
241 # The "kanban-md" spelling in these BEGIN/END markers (and the matching
242 # regex in _write_to_file below) is an intentional interop contract: karr
243 # and kanban-md maintain the same context block inside a shared host file
244 # (e.g. AGENTS.md) by matching identical sentinels, so switching tools
245 # updates the same block and leaves no orphaned markers. Do NOT rename to
246 # "karr".
247 my $md = "<!-- BEGIN kanban-md context -->\n";
248 $md .= "## Board: $board_name\n\n";
249 $md .= "**$total tasks** | $active active | $blocked blocked | $overdue overdue\n\n";
250  
251 my %section_title = (
252 'in-progress' => 'In Progress',
253 'blocked' => 'Blocked',
254 'overdue' => 'Overdue',
255 'recently-completed' => 'Recently Completed',
256 'activity' => 'Recent Activity',
257 );
258  
259 for my $sec (@$sections) {
260 $md .= "### " . ($section_title{$sec->{name}} // $sec->{name}) . "\n\n";
261 if ($sec->{name} eq 'activity') {
262 # An activity item is a log event, not a task -- it has no priority or
263 # assignee to report, so it gets its own line shape instead of being
264 # forced into _task_item's.
265 for my $item (@{$sec->{items}}) {
266 $md .= sprintf "- %s **%s** %s task#%s", $item->{ts} // '?',
267 $item->{agent} // '?', $item->{action} // '?', $item->{task_id} // '?';
268 $md .= " ($item->{detail})" if defined $item->{detail} && length $item->{detail};
269 $md .= "\n";
270 }
271 } else {
272 for my $item (@{$sec->{items}}) {
273 $md .= sprintf "- **#%d** %s (%s", $item->{id}, $item->{title}, $item->{priority};
274 $md .= ", \@$item->{assignee}" if $item->{assignee};
275 $md .= ")";
276 $md .= " \x{2014} $item->{note}" if $item->{note};
277 $md .= "\n";
278 }
279 }
280 $md .= "\n";
281 }
282  
283 $md .= "<!-- END kanban-md context -->\n";
284 return $md;
285 }
286  
287 sub _write_to_file {
288 my ($self, $md) = @_;
289 my $file = Path::Tiny::path($self->write_to);
290  
291 # Decide the whole file first, then write it once. --write into a directory
292 # karr may not write is the user's path, not karr's, and Path::Tiny's error
293 # would otherwise report this file and line at them (#77). A merely
294 # read-only target file still goes through: spew renames into place.
295 my $out = $md;
296 if ($file->exists) {
297 my $content = eval { $file->slurp_utf8 };
298 defined $content
299 or user_error( "Could not read $file: ", clean_error($@) );
300 if ($content =~ /<!-- BEGIN kanban-md context -->.*<!-- END kanban-md context -->/s) {
301 $content =~ s/<!-- BEGIN kanban-md context -->.*<!-- END kanban-md context -->\n?/$md/s;
302 $out = $content;
303 } else {
304 my $sep = $content =~ /\n$/ ? "\n" : "\n\n";
305 $out = $content . $sep . $md;
306 }
307 }
308  
309 eval { $file->spew_utf8($out); 1 }
310 or user_error( "Could not write $file: ", clean_error($@) );
311  
312 # stdout belongs to the payload when an output flag claims it, so the
313 # confirmation goes to stderr there. Same answer #248 gave for `delete`'s
314 # prompt and for the same reason: `karr context --json --write-to AGENTS.md
315 # > ctx.json` has to leave behind a file that decodes whole, and a
316 # key=value rendering that carries one line of prose is not key=value.
317 # Without an output flag stdout is prose anyway, so the line stays put.
318 if ( $self->json || $self->compact ) {
319 printf STDERR "Context written to %s\n", $self->write_to;
320 }
321 else {
322 printf "Context written to %s\n", $self->write_to;
323 }
324 }
325  
326 sub _task_item {
327 my ($self, $task, $note) = @_;
328 return {
329 id => $task->id,
330 title => $task->title,
331 status => $task->status,
332 priority => $task->priority,
333 # Empty means absent, as in pick and list (ticket #59): an `assignee: ""`
334 # from kanban-md must not become an "assignee":"" key in the --json
335 # payload. The Markdown renderer already tested truth rather than the
336 # predicate, so only --json ever saw it.
337 ( $task->has_assignee && length $task->assignee
338 ? ( assignee => $task->assignee )
339 : () ),
340 ($note ? (note => $note) : ()),
341 };
342 }
343  
344 # Cross-agent recent activity (ticket #92). #64 put every mutating command
345 # through the log, but context read none of it -- the log was still summarised
346 # purely from task state. Read via the same merged-refs walk `karr log` does,
347 # but bounded, because this is a briefing meant to stay short, not the log
348 # viewer: the whole log is what `karr log` is for.
349 #
350 # The bound excludes the invoking identity's own entries rather than
351 # truncating a merged view blindly. An agent about to pick up work already
352 # knows what it itself just did -- `karr show --me` is the tool for that --
353 # so what changes its decision is what *other* identities have been doing.
354 # Only the current-scheme refs are excluded; entries left on a pre-#75 legacy
355 # ref (see App::karr::ActivityLog) are rare enough, and old enough, that
356 # counting them as "someone else" costs nothing in practice.
357 #
358 # "The current-scheme refs" is plural and asked of the log itself (owns_ref),
359 # not compared against one ref name: since #171 an identity's log rotates into
360 # refs/karr/log/<role>/<email>+NNNNNN segments, and an equality test would have
361 # started reporting this agent's own older entries as another agent's the
362 # moment its log outgrew one segment.
363 sub _recent_activity {
364 my ($self) = @_;
365 my $git = $self->git;
366 my $log = $self->activity_log;
367  
368 my @entries;
369 for my $ref ($git->list_refs('refs/karr/log/')) {
370 next if $log->owns_ref($ref);
371 my $content = $git->read_ref($ref);
372 next unless defined $content && length $content;
373 for my $line (split /\n/, $content) {
374 next unless length $line;
375 my $decoded = eval { json_decode($line) };
376 push @entries, $git->maybe_repair_legacy($decoded) if $decoded;
377 }
378 }
379  
380 @entries = sort { ($a->{ts} // '') cmp ($b->{ts} // '') } @entries;
381 my $limit = $self->activity_limit;
382 @entries = @entries[-$limit .. -1] if $limit && @entries > $limit;
383  
384 # Newest first, like recently-completed -- the point of a briefing is that
385 # the most relevant items are the ones on top.
386 return map {
387 my $e = $_;
388 {
389 ts => $e->{ts},
390 agent => $e->{agent},
391 action => $e->{action},
392 task_id => $e->{task_id},
393 ( defined $e->{detail} && length $e->{detail} ? ( detail => $e->{detail} ) : () ),
394 }
395 } reverse @entries;
396 }
397  
398 # The in-progress section is the briefing's "what is being worked on right
399 # now", sorted most-urgent-first. The order comes from the board's own
400 # priorities list -- a hardcoded table used to give the wrong answer for any
401 # priority the default set did not know (ticket #149). Convention matches
402 # pick / kanban-md: higher index in the list = more urgent.
403 sub _pri_order {
404 my ($self, $task) = @_;
405 my @priorities = $self->config->priorities;
406 my %index;
407 $index{$priorities[$_]} //= $_ for 0 .. $#priorities;
408 my $max = $#priorities;
409 return $max - ( $index{ $task->priority } // -1 );
410 }
411  
412 sub _count_overdue {
413 my ($self, $tasks) = @_;
414 my $now = gmtime->strftime('%Y-%m-%d');
415 return scalar grep { $self->_is_overdue($_, $now) } @$tasks;
416 }
417  
418 # One overdue test for the count and the section, so the header can never
419 # disagree with the list under it.
420 #
421 # `due: ""` satisfies the predicate but is not a date, and the empty string
422 # sorts before every real one -- so a kanban-md card carrying it was reported
423 # overdue for ever, with "due " and nothing after it. Empty means absent, as it
424 # does in pick (ticket #59).
425 sub _is_overdue {
426 my ($self, $task, $now) = @_;
427 return 0 unless $task->has_due && length $task->due;
428 return 0 unless $task->due lt $now;
429 return !$self->store->is_terminal_status($task->status);
430 }
431  
432 sub _load_tasks {
433 my ($self) = @_;
434 return $self->load_tasks;
435 }
436  
437 1;
438  
439 __END__
« blib/lib/App/karr/Role/TaskMutation.pm ↑ Summary lib/App/karr/Git.pm »