blib/lib/App/karr/Cmd/Metrics.pm untested

filter: Statementstmt 0.0% 0 / 139 Branchbran 0.0% 0 / 80 Conditioncond 0.0% 0 / 79 MC/DCmcdc 0.0% 0 / 44 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 374 CC 41 SCAR 58.1
CC
41
Cov
0%
execute
756.0
_unusable_note
20.0
_epoch
20.0
CRAP 334.2
1 # ABSTRACT: Show flow metrics: throughput, lead/cycle time, flow efficiency, aging work
2  
3 package App::karr::Cmd::Metrics;
4 our $VERSION = '0.602';
5 use Moo;
6 use MooX::Cmd;
7 use MooX::Options (
8 usage_string => 'USAGE: karr metrics [--since YYYY-MM-DD] [--json] [--compact]',
9 );
10 use Time::Piece;
11 use App::karr::Role::BoardAccess;
12 use App::karr::Role::Output;
13 use App::karr::Role::CompactOutput;
14 use App::karr::Config;
15  
16 with 'App::karr::Role::BoardAccess', 'App::karr::Role::Output',
17 'App::karr::Role::CompactOutput';
18  
19  
20 option since => (
21 is => 'ro',
22 format => 's',
23 doc => 'Only count tasks completed after this date (YYYY-MM-DD)',
24 );
25  
26  
27 use constant SHORT_WINDOW_DAYS => 7;
28 use constant LONG_WINDOW_DAYS => 30;
29 use constant SECONDS_PER_HOUR => 3600;
30 use constant SECONDS_PER_DAY => 86400;
31  
32 sub execute {
33 my ($self, $args_ref, $chain_ref) = @_;
34  
35 # Option validation first, so a bad --since still exits 2 on a repository
36 # that has no board (ADR 0002, the ordering require_local_board documents).
37 my $since;
38 if ( defined $self->since && length $self->since ) {
39 eval { App::karr::Config->validate_due( $self->since ); 1 }
40 or $self->usage_error(
41 sprintf 'invalid --since date "%s" (expected YYYY-MM-DD)', $self->since );
42 $since = _epoch( $self->since );
43 }
44  
45 # Zeroes over an unread board would be the most confident possible way to be
46 # wrong here: "throughput 0" reads as a board that shipped nothing, not as a
47 # board that was never fetched (#135).
48 $self->require_local_board;
49  
50 my $now = gmtime->epoch;
51 my $window_short = $now - SHORT_WINDOW_DAYS * SECONDS_PER_DAY;
52 my $window_long = $now - LONG_WINDOW_DAYS * SECONDS_PER_DAY;
53  
54 # Archived work is out of every figure, as it is out of `list` and `board`
55 # (and out of kanban-md's metrics, which filters on IsArchivedStatus).
56 my @tasks = grep { $_->status ne App::karr::Config->ARCHIVED_STATUS }
57 $self->load_tasks;
58  
59 my ( $throughput_short, $throughput_long ) = ( 0, 0 );
60 my ( $lead_sum, $lead_n, $cycle_sum, $cycle_n, $paired_lead_sum ) = ( 0, 0, 0, 0, 0 );
61 my @aging;
62 my $unusable = 0;
63 my $negative_lead = 0;
64  
65 for my $task (@tasks) {
66 my $created = _epoch( $task->created );
67 my $started = $task->has_started ? _epoch( $task->started ) : undef;
68 my $completed = $task->has_completed ? _epoch( $task->completed ) : undef;
69  
70 # kanban-md filters the task list before computing; the effect is the same
71 # and this keeps the parse in one place. Strictly after, as there: a task
72 # completed at midnight of the --since date is not "after" it. A task with
73 # no completion is kept either way, which is what leaves the aging list
74 # unaffected by --since.
75 next if defined $since && defined $completed && $completed <= $since;
76  
77 # A start that precedes the card's own creation is not a start anything can
78 # be measured from. karr before 0.403 stamped `started` as a bare date
79 # (ticket #68), which reads as midnight and so precedes a card created later
80 # the same day: 75 of the 116 finished tickets on karr's own board carry one.
81 # Counted, the cycle time of such a card exceeds its lead time, and the
82 # board reports a flow efficiency above 100% -- exactly the confidently
83 # wrong number this command exists not to print. The stamp is still good
84 # enough to say the work is in flight, so aging below uses it either way.
85 my $start_measurable =
86 defined $started && ( !defined $created || $started >= $created );
87  
88 # And a completion that precedes that start is not the end of a cycle: a
89 # cycle time may not be negative. The check above used to catch these cards
90 # by their start alone, because a board old enough to hold a bare-date
91 # `completed` holds bare-date `started` stamps too -- until `karr repair`
92 # (ticket #138) raised those starts to `created`, after which the start
93 # check passes by construction and the impossible order lands here instead.
94 # Unguarded that was 42 negative samples out of 117 on karr's own board,
95 # averaging to a cycle time of 16 minutes (ticket #140). The lead time of
96 # such a card gets no symmetric guard: it is qualified rather than excluded,
97 # for the reason on $negative_lead below (ticket #139).
98 my $cycle_measurable =
99 $start_measurable && defined $completed && $completed >= $started;
100  
101 # Counted once per task, not once per stamp: what the reader needs to know
102 # is how many cards are missing from the figures below. Counted after the
103 # --since filter, so a card the caller asked to leave out is not reported
104 # as one karr could not use.
105 $unusable++
106 if !defined $created
107 || ( $task->has_started && !defined $started )
108 || ( $task->has_completed && !defined $completed )
109 || ( defined $started && !$start_measurable )
110 || ( defined $completed && $start_measurable && !$cycle_measurable );
111  
112 if ( defined $completed ) {
113 $throughput_short++ if $completed > $window_short;
114 $throughput_long++ if $completed > $window_long;
115  
116 if ( defined $created ) {
117 my $lead = ( $completed - $created ) / SECONDS_PER_HOUR;
118 $lead_sum += $lead;
119 $lead_n++;
120 # Deliberately still summed in. `created` and `completed` are original
121 # data -- unlike `started`, which karr manufactured and #138 rewrote --
122 # so a negative lead time is evidence of a bad completion, and there is
123 # no value to clamp it to that would not be an invention: `created` is
124 # too early, `started` asserts a zero cycle time, and the end of the day
125 # a bare date bounds was never written down. The sample stays and gets
126 # counted instead, so the average is qualified rather than cleaned
127 # (ticket #139). Not folded into $unusable: that counter means "missing
128 # from an average", and this card is missing from nothing.
129 $negative_lead++ if $lead < 0;
130 if ($cycle_measurable) {
131 $cycle_sum += ( $completed - $started ) / SECONDS_PER_HOUR;
132 $cycle_n++;
133 # The efficiency denominator: the lead time of the same tasks the
134 # cycle time was measured over. See the flow-efficiency entry in the
135 # POD above for why this is not simply $lead_sum.
136 $paired_lead_sum += $lead;
137 }
138 }
139 }
140  
141 # Started, still open, no completion recorded. has_completed rather than
142 # the parsed stamp on purpose: a card whose completion is merely unreadable
143 # is finished work, and reporting it as aging would age it for ever. A
144 # bare-date start is good enough here (an age measured in days is not
145 # changed by which hour of the day the work began), which is why this asks
146 # `defined $started` and not $start_measurable.
147 if ( defined $started
148 && !$task->has_completed
149 && !$self->store->is_terminal_status( $task->status ) )
150 {
151 push @aging, {
152 id => $task->id + 0,
153 title => $task->title,
154 status => $task->status,
155 age_hours => _round( ( $now - $started ) / SECONDS_PER_HOUR, 2 ),
156 };
157 }
158 }
159  
160 # Oldest first: refs come back unordered, so without this the list would
161 # shuffle between runs, and the item that most needs attention is the one
162 # that has been in flight longest.
163 @aging = sort { $b->{age_hours} <=> $a->{age_hours} || $a->{id} <=> $b->{id} } @aging;
164  
165 my $avg_lead = $lead_n ? $lead_sum / $lead_n : undef;
166 my $avg_cycle = $cycle_n ? $cycle_sum / $cycle_n : undef;
167 my $efficiency =
168 ( $cycle_n && $paired_lead_sum > 0 ) ? $cycle_sum / $paired_lead_sum : undef;
169  
170 # Order matters: the lead caveat qualifies a figure that is printed, so it
171 # comes before the one that says what was left out entirely.
172 my @notes = (
173 ( $negative_lead ? _negative_lead_note( $negative_lead, $lead_n ) : () ),
174 ( $unusable ? _unusable_note($unusable) : () ),
175 );
176  
177 if ( $self->json ) {
178 $self->print_json( {
179 throughput_7d => $throughput_short,
180 throughput_30d => $throughput_long,
181 lead_samples => $lead_n,
182 cycle_samples => $cycle_n,
183 unusable_timestamps => $unusable,
184 negative_lead_samples => $negative_lead,
185 aging_items => \@aging,
186 ( defined $avg_lead ? ( avg_lead_time_hours => _round( $avg_lead, 2 ) ) : () ),
187 ( defined $avg_cycle ? ( avg_cycle_time_hours => _round( $avg_cycle, 2 ) ) : () ),
188 ( defined $efficiency ? ( flow_efficiency => _round( $efficiency, 4 ) ) : () ),
189 } );
190 return;
191 }
192  
193 if ( $self->compact ) {
194 printf "Throughput: %d/7d %d/30d | Lead: %s | Cycle: %s | Efficiency: %s\n",
195 $throughput_short, $throughput_long,
196 _duration_or_dash($avg_lead), _duration_or_dash($avg_cycle),
197 _percent_or_dash($efficiency);
198 printf "Aging: #%d [%s] %s (%s)\n",
199 $_->{id}, $_->{status}, $_->{title}, _format_duration( $_->{age_hours} )
200 for @aging;
201 print join "\n", @notes if @notes;
202 return;
203 }
204  
205 print "# Flow Metrics\n\n";
206 printf "%-17s%s\n", 'Throughput 7d:', _count_label($throughput_short);
207 printf "%-17s%s\n", 'Throughput 30d:', _count_label($throughput_long);
208 printf "%-17s%s\n", 'Avg lead time:', _average_label( $avg_lead, $lead_n );
209 printf "%-17s%s\n", 'Avg cycle time:', _average_label( $avg_cycle, $cycle_n );
210 printf "%-17s%s\n", 'Flow efficiency:', _percent_or_dash($efficiency);
211  
212 if (@aging) {
213 print "\n## Aging Work Items\n\n";
214 printf "- %d | %s | %s | age:%s\n",
215 $_->{id}, $_->{title}, $_->{status}, _format_duration( $_->{age_hours} )
216 for @aging;
217 }
218  
219 # An empty board must say what it means. Every figure above is legitimately
220 # blank in that state, and a page of dashes and zeroes reads like a bug.
221 print "\nNothing to measure yet: no task on this board carries a start or a\n"
222 . "completion stamp.\n"
223 if !$lead_n && !$cycle_n && !@aging;
224  
225 print "\n", join( "\n", @notes ) if @notes;
226 }
227  
228 # What the lead average rests on. The samples are in the figure above by
229 # design (see the comment on $negative_lead), which is exactly why they have to
230 # be named here: an unclamped impossible number that nothing points at reads as
231 # a measurement.
232 sub _negative_lead_note {
233 my ( $count, $samples ) = @_;
234 return sprintf
235 "Note: %d of the %d lead times behind the average above %s negative -- a\n"
236 . "`completed` that precedes the card's own `created`. Nothing is clamped, so\n"
237 . "the average reads lower than the work took. A karr older than 0.403 stamped\n"
238 . "`completed` as a bare date, read here as midnight: on such a board an\n"
239 . "average printed to the hour is finer than the data underneath it.\n",
240 $count, $samples, ( $count == 1 ? 'is' : 'are' );
241 }
242  
243 # What the averages left out, and why. Never silent: a card missing from a
244 # figure is the one thing a metrics command must not hide.
245 sub _unusable_note {
246 my ($count) = @_;
247 return sprintf
248 "Note: %d task%s carr%s a timestamp karr could not use -- unreadable, a\n"
249 . "start that precedes the card's own creation, or a completion that\n"
250 . "precedes that start -- and %s left out of the averages that need it.\n",
251 $count, ( $count == 1 ? '' : 's' ), ( $count == 1 ? 'ies' : 'y' ),
252 ( $count == 1 ? 'is' : 'are' );
253 }
254  
255 sub _count_label {
256 my ($count) = @_;
257 return sprintf '%d task%s', $count, ( $count == 1 ? '' : 's' );
258 }
259  
260 sub _average_label {
261 my ( $hours, $samples ) = @_;
262 return '--' unless defined $hours;
263 return sprintf '%s (over %d task%s)', _format_duration($hours), $samples,
264 ( $samples == 1 ? '' : 's' );
265 }
266  
267 sub _duration_or_dash {
268 my ($hours) = @_;
269 return defined $hours ? _format_duration($hours) : '--';
270 }
271  
272 sub _percent_or_dash {
273 my ($ratio) = @_;
274 return defined $ratio ? sprintf( '%.1f%%', $ratio * 100 ) : '--';
275 }
276  
277 # kanban-md's FormatDuration (internal/output/table.go): days and hours once
278 # there is a whole day, hours and minutes below that, truncated rather than
279 # rounded. The sign is handled here and not there, because a hand-edited card
280 # can carry a completion older than its creation, and Perl's % on a negative
281 # operand would turn that into a nonsense figure rather than a negative one.
282 sub _format_duration {
283 my ($hours) = @_;
284 my $sign = $hours < 0 ? '-' : '';
285 $hours = abs $hours;
286 my $whole_hours = int $hours;
287 my $days = int( $whole_hours / 24 );
288 my $rest_hours = $whole_hours % 24;
289 return sprintf '%s%dd %dh', $sign, $days, $rest_hours if $days > 0;
290 return sprintf '%s%dh %dm', $sign, $rest_hours, int( $hours * 60 ) % 60;
291 }
292  
293 sub _round {
294 my ( $value, $places ) = @_;
295 # Through sprintf and back into a number, so --json carries 2.34 rather than
296 # 2.3399999999999999 and the same run always prints the same digits.
297 return 0 + sprintf( "%.${places}f", $value );
298 }
299  
300 # Every timestamp shape a karr board can hold, as epoch seconds, or undef when
301 # the value is none of them.
302 #
303 # * karr's own writer: 2026-08-12T09:41:03Z
304 # * kanban-md's: 2026-08-12T11:41:03.449764553+02:00 (RFC3339Nano,
305 # local offset, sub-second precision)
306 # * a pre-0.403 karr `started`, and any hand-written date: 2026-08-12
307 #
308 # App::karr::Role::ClaimTimeout parses the first two for claim expiry and has
309 # the long-form reasoning; this is the same grammar with the bare date added,
310 # which that role deliberately does not accept (a claim stamp is never one).
311 # Duplicated rather than shared because the role's parser is private to it and
312 # answers a different question -- see the report on ticket #126.
313 #
314 # Sub-second precision is dropped: nothing here is measured in less than a
315 # minute. An offset-less stamp is read as UTC, which is what karr's own writer
316 # means by it.
317 sub _epoch {
318 my ($stamp) = @_;
319 return undef unless defined $stamp && length $stamp;
320 my ( $date, $time, $offset ) = $stamp =~ m{
321 \A (\d{4}-\d{2}-\d{2}) # calendar date
322 (?: T (\d{2}:\d{2}:\d{2}) # civil time, optional
323 (?: \. \d+ )? # fractional seconds, dropped
324 ( Z | [+-]\d{2}:?\d{2} )? # UTC offset, or none
325 )?
326 \z
327 }x or return undef;
328 $time //= '00:00:00';
329 # Time::Piece's %z wants +hhmm and does not know "Z" at all.
330 $offset = '+0000' if !defined $offset || uc($offset) eq 'Z';
331 $offset =~ s/://;
332 my $parsed =
333 eval { Time::Piece->strptime( "${date}T${time}${offset}", '%Y-%m-%dT%H:%M:%S%z' ) };
334 return defined $parsed ? $parsed->epoch : undef;
335 }
336  
337 1;
338  
339 __END__