diff --git a/.rubocop.yml b/.rubocop.yml index 3bac330..4aee1ac 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -20,9 +20,12 @@ Metrics/MethodLength: Max: 25 Exclude: - "lib/plan_driven/configuration.rb" + - "lib/plan_driven/charts.rb" + - "lib/plan_driven/renderer/html.rb" # CLI commands read top to bottom as the conversation they print, and the Markdown and -# Gherkin readers are line-by-line state machines. Splitting them would hide the flow. +# Gherkin readers are line-by-line state machines. Splitting them would hide the flow. A chart +# is one drawing: its coordinates read best in one place. Metrics/AbcSize: Max: 30 Exclude: @@ -30,6 +33,7 @@ Metrics/AbcSize: - "lib/plan_driven/renderer/html.rb" - "lib/plan_driven/gherkin.rb" - "lib/plan_driven/configuration.rb" + - "lib/plan_driven/charts.rb" Metrics/CyclomaticComplexity: Max: 12 @@ -81,6 +85,8 @@ Naming/MethodParameterName: - at - by - pr + - x + - y Naming/PredicateMethod: AllowedMethods: diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c897b4..c502cd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,25 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added + +- Statistics, computed from the audit trail: how long planning, tickets, development and proof + took, each ticket's time split into queued, agent coding, waiting for review, agent fixing + feedback and approved but not merged, the agents' share of the work, first-time approvals, + and acceptance criteria merged and proven over time. `plan-driven stats PLAN` prints them, + the wizard has a Statistics page with charts, and the delivery report has a Statistics + section. +- Charts drawn in Ruby as SVG, with no JavaScript: a burn-up of criteria merged and proven, + a timeline of each ticket, the split between agents and people, and a bar of every + criterion's result. The delivery report writes them next to the Markdown, so GitHub shows + them, and inlines them in the HTML and the PDF. + +### Changed + +- The delivery report has colour: every acceptance criterion's result is a green, red, amber + or grey pill with a matching edge on its row, failed rows are tinted red, merged tickets are + marked green, and the Markdown shows ✅, ❌, ⏸️ or ⚠️ before each result. + ## [0.2.0] - 2026-09-30 ### Added diff --git a/README.md b/README.md index 855b9dd..4929119 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ repository. The planner and the five agents ran on Claude Opus 5.5 through Curso - [Configuration](#configuration) - [Choosing the coding agents](#choosing-the-coding-agents) - [Tokens and cost](#tokens-and-cost) +- [Statistics](#statistics) - [How it compares](#how-it-compares) - [Keys](#keys) - [Working as a team](#working-as-a-team) @@ -717,8 +718,9 @@ $ bin/plan-driven report PD-1 `evidence` runs the plan's scenarios on your machine and stores the result with the commit it ran on; `--from cucumber.json` imports a run from CI instead. The delivery report lists each -ticket with its pull request, merge commit and approver, then every acceptance criterion with -the scenario that proves it, the guard findings, every approval and the full timeline. Commit +ticket with its pull request, merge commit and approver, the [statistics](#statistics) with +their charts, then every acceptance criterion with the scenario that proves it, marked passed +or failed in colour, the guard findings, every approval and the full timeline. Commit `docs/plans/` with it, and the plan and its proof stay next to the code. ![The delivery report](docs/images/15-delivery-report.png) @@ -840,6 +842,7 @@ key such as `PD-1`, and `PLAN/TICKET` is a ticket such as `PD-1/T3`. | `report PLAN` | Write the delivery report | | `log PLAN` | The audit trail | | `usage PLAN` | Tokens, time and cost per step and per agent run | +| `stats PLAN` | Where the time went: phases, agents and people, each ticket | | `questions` | The interview's questions, and which ones the team changed or added | | `question KEY [--title T] [--ask Q] [--group G] [--required \| --optional] [--remove]` | Change or add an interview question, or put it back | | `configure` | Store keys in `~/.plan_driven/config` | @@ -985,6 +988,90 @@ For scale, these are the five cloud agents from the demo, read back from Cursor' are code and text the agents wrote. Most of an agent's tokens go into reading the codebase, so a small, conventional one is cheaper to work on. +## Statistics + +Where did the time go? Was it the agents writing code, or the pull requests waiting for a +person? The same numbers are in three places: + +- **In the wizard:** every plan has a Statistics page, linked under its title and from the + Proof & report step. In development that's `http://localhost:3000/plan_driven/plans/PD-1/statistics`. +- **In the terminal:** `bin/plan-driven stats PD-1`. +- **In the delivery report:** a Statistics section with the same charts, in the Markdown, the + HTML and the PDF. + +![The Statistics page in the wizard, for a delivered plan](docs/images/statistics.png) + +This is PD-3 from the demo: six tickets delivered in 1 h 20 min, 42 of 42 criteria proven. + +- **Cards:** idea to delivery, development time, criteria proven, pull requests approved the + first time, the agents' share of the work, and tokens. +- **Acceptance criteria, merged and proven:** a burn-up against the plan's scope. The blue + line rises as each ticket merges with its criteria, and the green line rises when an + evidence run proves them. Every run is a dot, red when it failed. Here, two runs failed + around 14:50 and the third proved all 42. +- **Where the time went, ticket by ticket:** one row per ticket on a shared clock. Grey is + queued, waiting for the tickets it depends on. Blue is an agent coding, amber is the pull + request waiting for review, purple is an agent fixing feedback, and green is approved but + not merged. T3 has one round of feedback, and each ticket waited for the one before it. +- **Agents and people:** how the time tickets were worked on splits. Here agents took 91% of + it and reviews took 7%. On a plan where the donut is mostly amber, the bottleneck is review, + not code. +- **Ticket by ticket, and the phases:** the same times as a table, with the estimate and the + review rounds, and how long planning, tickets, development and proof took. + +``` +$ bin/plan-driven stats PD-3 +PD-3 Comments on events: statistics + Planning 2 min + Tickets 2 min + Development 1 h 20 min + Proof 10 min + Idea to delivery 1 h 25 min + Tickets merged 6 of 6, 5 approved the first time +✓ 42 of 42 acceptance criteria proven + +Where the time went while tickets were worked on (agents 91%): + Agent coding 1 h 2 min ████████████████████ 79% + Waiting for review 5 min ██ 7% + Agent fixing feedback 9 min ███ 12% + Approved, not merged 1 min █ 2% + +# Est Queued Agent Review Fixes Merge Rounds Total +T1 2 53s 10 min 4 min - 23s 0 16 min +T2 2 17 min 10 min 8s - 12s 0 10 min +T3 3 28 min 11 min 28s 9 min 10s 1 21 min +... +``` + +### How it's worked out + +Nothing is estimated, and no model is asked. Every number is the time between two events that +plan-driven already records in the audit trail: + +| From | To | Counts as | +| --- | --- | --- | +| `tickets.approved` | `ticket.agent_started` | Queued | +| `ticket.agent_started` | `ticket.pr_opened` | Agent coding | +| `ticket.pr_opened` | `ticket.pr_approved` or `ticket.changes_requested` | Waiting for review | +| `ticket.changes_requested` | the next `ticket.pr_opened` | Agent fixing feedback | +| `ticket.pr_approved` | `ticket.merged` | Approved, not merged | + +The phases run from `plan.drafted` to the last `plan.approved` (planning), then to +`tickets.approved` (tickets), then to `plan.delivered` (development), then to the first +passing evidence run (proof). A plan still in development is counted up to now. A plan whose +tickets aren't approved yet shows only its planning time. + +The charts are SVG drawn in Ruby, with no JavaScript and nothing to install. `report` writes +them next to `delivery-report.md` (`statistics-burnup.svg`, `statistics-timeline.svg`, +`statistics-time.svg`, `statistics-proof.svg`), so GitHub shows them in the Markdown, and it +inlines them in the HTML and the PDF so both stand alone. + +The report also marks every acceptance criterion's result in colour: a green, red, amber or +grey pill with a matching edge on its row, and failed rows tinted red. On GitHub, the Markdown +shows ✅, ❌, ⏸️ or ⚠️ instead. + +![Acceptance criteria and proof in the delivery report](docs/images/statistics-report.png) + ## How it compares plan_driven sits next to spec-driven tools such as GitHub's Spec Kit and Kiro, which also start diff --git a/app/controllers/plan_driven/wizard/plans_controller.rb b/app/controllers/plan_driven/wizard/plans_controller.rb index b3e79d8..be37c25 100644 --- a/app/controllers/plan_driven/wizard/plans_controller.rb +++ b/app/controllers/plan_driven/wizard/plans_controller.rb @@ -6,7 +6,7 @@ module PlanDriven module Wizard # Every form posts here, and every post becomes one `plan-driven` command. The pages only read. class PlansController < ApplicationController - before_action :find_plan, only: %i[show run file] + before_action :find_plan, only: %i[show statistics run file] def index @plans = Plan.order(id: :desc) @@ -33,12 +33,16 @@ def show @template = PlanDriven.configuration.template end + def statistics + @step = "statistics" + @stats = Statistics.new(@plan) + end + def run job = start(Commands.argv(params[:do], command_fields)) - redirect_to plan_path(@plan.key, params[:step].presence, job: job.id, open: params[:open].presence, - anchor: params[:open].presence) + redirect_to after_run(job) rescue ArgumentError => e - redirect_to plan_path(@plan.key, params[:step].presence), alert: e.message + redirect_to plan_path(@plan.key, params[:step].presence.presence_in(Steps.keys)), alert: e.message end def run_global @@ -62,6 +66,13 @@ def file private + def after_run(job) + return plan_statistics_path(@plan.key, job: job.id) if params[:step] == "statistics" + + plan_path(@plan.key, params[:step].presence, job: job.id, open: params[:open].presence, + anchor: params[:open].presence) + end + def find_plan @plan = Plan.find_by_reference!(params[:key]) rescue ActiveRecord::RecordNotFound => e diff --git a/app/views/layouts/plan_driven/wizard/application.html.erb b/app/views/layouts/plan_driven/wizard/application.html.erb index 2fbb690..6acc79a 100644 --- a/app/views/layouts/plan_driven/wizard/application.html.erb +++ b/app/views/layouts/plan_driven/wizard/application.html.erb @@ -64,6 +64,18 @@ .grid2 { display:grid; grid-template-columns:minmax(0, 1fr) minmax(0, 2fr); gap:12px; } label.check { display:inline-flex; gap:6px; align-items:center; font-weight:400; margin:0; } .card.unused { opacity:.75; } + .kpis { display:grid; grid-template-columns:repeat(auto-fill, minmax(170px, 1fr)); gap:10px; margin:16px 0 4px; } + .kpi { background:#fff; border:1px solid var(--line); border-top:3px solid #3b82f6; border-radius:10px; padding:12px 14px; display:flex; flex-direction:column; gap:2px; } + .kpi small { color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:.04em; } + .kpi strong { font-size:26px; line-height:1.15; } .kpi strong span { font-size:16px; color:var(--muted); font-weight:500; } + .kpi .muted { font-size:12px; } + .kpi.good { border-top-color:var(--ok); } .kpi.good strong { color:var(--ok); } + .kpi.bad { border-top-color:var(--bad); } .kpi.bad strong { color:var(--bad); } + .card.chart { padding:6px; } .card.chart svg { display:block; width:100%; height:auto; } + .swatch { display:inline-block; width:8px; height:8px; border-radius:2px; margin-right:6px; vertical-align:middle; } + .phases { display:flex; gap:0; border-radius:8px; overflow:hidden; border:1px solid var(--line); } + .phases div { flex:1; padding:10px 12px; border-right:1px solid var(--line); display:flex; flex-direction:column; } + .phases div:last-child { border-right:0; } .phases small { color:var(--muted); } .phases .pending { background:#f9fafb; color:var(--muted); } .flash { padding:10px 14px; border-radius:8px; margin-bottom:12px; background:#fee2e2; color:var(--bad); } diff --git a/app/views/plan_driven/wizard/plans/_finish.html.erb b/app/views/plan_driven/wizard/plans/_finish.html.erb index 975031d..dbfe002 100644 --- a/app/views/plan_driven/wizard/plans/_finish.html.erb +++ b/app/views/plan_driven/wizard/plans/_finish.html.erb @@ -15,6 +15,13 @@ <% end %> +
+ Statistics + Where the time went, criteria merged and proven, agents and people. + + <%= link_to "Open the statistics →", plan_statistics_path(@plan.key), class: "button" %> +
+ <% files = %w[delivery-report.html delivery-report.pdf].select { |name| PlanDriven::Renderer.directory(@plan).join(name).file? } %> <% if files.any? %>
diff --git a/app/views/plan_driven/wizard/plans/show.html.erb b/app/views/plan_driven/wizard/plans/show.html.erb index dd5d48d..978d409 100644 --- a/app/views/plan_driven/wizard/plans/show.html.erb +++ b/app/views/plan_driven/wizard/plans/show.html.erb @@ -4,6 +4,7 @@

"><%= @plan.status.tr("_", " ") %> revision <%= @plan.revision %> · <%= PlanDriven::Workflow::PLAN_DESCRIPTIONS[@plan.status] %> + · <%= link_to "Statistics", plan_statistics_path(@plan.key) %>

    diff --git a/app/views/plan_driven/wizard/plans/statistics.html.erb b/app/views/plan_driven/wizard/plans/statistics.html.erb new file mode 100644 index 0000000..82ae372 --- /dev/null +++ b/app/views/plan_driven/wizard/plans/statistics.html.erb @@ -0,0 +1,94 @@ +<% content_for :title, "#{@plan.key} statistics" %> +<% duration = ->(seconds) { PlanDriven::Statistics.duration(seconds) } %> +

    <%= link_to "← #{@plan.key} #{@plan.title}", plan_path(@plan.key) %>

    +

    Statistics

    +

    + "><%= @plan.status.tr("_", " ") %> + Computed from the audit trail: every number is a recorded event, nothing is estimated. +

    + +<% if @stats.started? %> + <% s = @stats.summary %> +
    +
    + Idea to delivery + <%= duration[s[:lead_time]] %> + <%= @plan.status == "delivered" ? "plan drafted to delivered" : "so far" %> +
    +
    + Development + <%= duration[s[:development]] %> + <%= s[:merged] %> of <%= s[:tickets] %> tickets merged +
    +
    "> + Criteria proven + <%= s[:proven] %> / <%= s[:criteria] %> + <%= s[:evidence] ? "by a passing scenario" : "no evidence run yet" %> +
    +
    + Approved the first time + <%= s[:first_time] %> / <%= s[:merged] %> + <%= pluralize(s[:review_rounds], "review round") %> +
    +
    + Agents' share of the work + <%= s[:agent_share] ? "#{s[:agent_share]}%" : "-" %> + the rest is waiting on people +
    +
    + Tokens + <%= PlanDriven::Usage.format_tokens(s[:tokens]) %> + <%= s[:cost] ? PlanDriven::Usage.format_cost(s[:cost]) : "set config.token_prices for dollars" %> +
    +
    + + <% charts = PlanDriven::Charts.report(@plan, stats: @stats) %> + <% %w[statistics-proof.svg statistics-burnup.svg statistics-timeline.svg statistics-time.svg].each do |name| %> + <% next unless charts[name] %> +
    <%= charts[name].html_safe %>
    + <% end %> + +
    +

    Ticket by ticket

    + + + + + + <% @stats.tickets.each do |row| %> + + + + + <% %w[queued agent review fixes merge].each do |phase| %> + + <% end %> + + + + <% end %> + +
    #TicketEst.QueuedAgentReviewFixesMergeRoundsStart to merge
    <%= row.ticket.key %><%= row.ticket.title %><%= row.ticket.estimate %><%= row.seconds(phase).positive? ? duration[row.seconds(phase)] : "-" %><%= row.review_rounds %><% if row.merged? %><%= duration[row.cycle_time] %><% else %><%= row.ticket.status.tr("_", " ") %><% end %>
    +
    +<% else %> +
    + Statistics start when the tickets are approved. +

    Until then, this is how long planning has taken.

    +
    +<% end %> + +
    +

    Phases

    +
    + <% @stats.phases.each do |label, seconds| %> +
    "><%= label %><%= seconds ? duration[seconds] : "not yet" %>
    + <% end %> +
    +
    + +
    + The same numbers in the terminal, and the charts in the delivery report. + + <%= run_button "Print in the terminal", "stats" %> + <%= run_button "Write the delivery report", "report", {}, primary: true %> +
    diff --git a/config/routes.rb b/config/routes.rb index 04319e4..9a141c8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -3,6 +3,7 @@ PlanDriven::Wizard::Engine.routes.draw do root "plans#index" resources :plans, only: %i[new create], param: :key + get "plans/:key/statistics", to: "plans#statistics", as: :plan_statistics get "plans/:key(/:step)", to: "plans#show", as: :plan, constraints: { step: /plan|approve|tickets|agents|finish/ } post "plans/:key/run", to: "plans#run", as: :run_plan get "plans/:key/files/:name", to: "plans#file", as: :plan_file, constraints: { name: /[a-z-]+\.(pdf|html)/ } diff --git a/docs/images/statistics-report.png b/docs/images/statistics-report.png new file mode 100644 index 0000000..20b1d7b Binary files /dev/null and b/docs/images/statistics-report.png differ diff --git a/docs/images/statistics.png b/docs/images/statistics.png new file mode 100644 index 0000000..3b57c80 Binary files /dev/null and b/docs/images/statistics.png differ diff --git a/lib/plan_driven.rb b/lib/plan_driven.rb index 363137c..0e73d65 100644 --- a/lib/plan_driven.rb +++ b/lib/plan_driven.rb @@ -31,8 +31,10 @@ require_relative "plan_driven/local_agents" require_relative "plan_driven/usage" require_relative "plan_driven/repository" -require_relative "plan_driven/renderer" require_relative "plan_driven/evidence" +require_relative "plan_driven/statistics" +require_relative "plan_driven/charts" +require_relative "plan_driven/renderer" require_relative "plan_driven/delivery" require_relative "plan_driven/wizard" require_relative "plan_driven/railtie" if defined?(Rails::Railtie) diff --git a/lib/plan_driven/charts.rb b/lib/plan_driven/charts.rb new file mode 100644 index 0000000..6860139 --- /dev/null +++ b/lib/plan_driven/charts.rb @@ -0,0 +1,252 @@ +# frozen_string_literal: true + +require "cgi" + +module PlanDriven + # A plan's statistics as SVG, drawn in Ruby. The same file shows in the wizard, on GitHub next + # to the delivery report and in its PDF: no JavaScript, nothing to install. + module Charts + COLORS = { + "queued" => "#d1d5db", "agent" => "#3b82f6", "review" => "#f59e0b", "fixes" => "#8b5cf6", + "merge" => "#10b981", "passed" => "#16a34a", "failed" => "#dc2626", "not run" => "#f59e0b", + "no scenario" => "#9ca3af" + }.freeze + INK = "#1f2330" + MUTED = "#6b7280" + GRID = "#eef0f3" + FONT = "-apple-system, 'Segoe UI', Helvetica, Arial, sans-serif" + TICKS = [60, 300, 600, 900, 1800, 3600, 7200, 10_800, 21_600, 43_200, 86_400, 172_800, 604_800].freeze + STATUSES = ["passed", "failed", "not run", "no scenario"].freeze + + # The report's charts by file name, leaving out any the plan has no data for yet. + def self.report(plan, stats: Statistics.new(plan)) + { "statistics-proof.svg" => proof(Evidence.matrix(plan)), "statistics-burnup.svg" => burnup(stats), + "statistics-timeline.svg" => timeline(stats), "statistics-time.svg" => breakdown(stats) }.compact + end + + module_function + + # Criteria merged (blue) and proven by a passing test (green), against the plan's scope. + def burnup(stats) + data = stats.burnup or return + width = 760 + height = 320 + box = { left: 44, right: 24, top: 84, bottom: 36 } + x = scale_time(data[:from], data[:to], box[:left], width - box[:right]) + top = [data[:scope], 1].max + y = ->(value) { box[:top] + ((1 - (value.to_f / top)) * (height - box[:top] - box[:bottom])) } + parts = [heading("Acceptance criteria, merged and proven", "#{data[:scope]} in scope")] + parts << legend([["Merged", COLORS["agent"]], ["Proven by a passing test", COLORS["passed"]], + ["Scope", MUTED]], 20, 70) + parts << value_grid(top, y, box[:left], width - box[:right]) + parts << time_axis(data[:from], data[:to], x, height - box[:bottom], box[:top]) + parts << (%()) + parts << step_series(data[:merged], data[:to], x, y, COLORS["agent"], fill: true) + parts << step_series(data[:proven], data[:to], x, y, COLORS["passed"]) + parts << run_dots(data[:proven].drop(1), x, y) + svg(width, height, parts.join("\n"), title: "Acceptance criteria merged and proven over time") + end + + # One row per ticket on a shared clock: queued, agent coding, waiting for review, fixing + # feedback, approved but not merged. + def timeline(stats) + rows = stats.tickets.select { |row| row.segments.any? } + return if rows.empty? + + from, to = stats.window + width = 760 + box = { left: 190, right: 100, top: 84, bottom: 36 } + row_height = 30 + height = box[:top] + (rows.size * row_height) + box[:bottom] + x = scale_time(from, to, box[:left], width - box[:right]) + phases = Statistics::PHASES.select { |phase, _| rows.any? { |row| row.seconds(phase).positive? } } + parts = [heading("Where the time went, ticket by ticket", "#{Statistics.duration(to - from)} in development")] + parts << legend(phases.map { |phase, label| [label, COLORS[phase]] }, 20, 70) + parts << time_axis(from, to, x, height - box[:bottom], box[:top]) + rows.each_with_index do |row, index| + parts << ticket_row(row, box[:top] + (index * row_height), x, box[:left]) + end + svg(width, height, parts.join("\n"), title: "Where the time went, ticket by ticket") + end + + # How the time tickets were worked on splits between agents and people. + def breakdown(stats) + totals = stats.totals.slice(*Statistics::WORK).select { |_, seconds| seconds.positive? } + sum = totals.values.sum + return if sum.zero? + + width = 760 + height = 250 + center = [130, 150] + radius = 72 + circumference = 2 * Math::PI * radius + offset = 0.0 + rings = totals.map do |phase, seconds| + length = circumference * seconds / sum + ring = %() + + %(#{esc(Statistics::PHASES[phase])}: #{Statistics.duration(seconds)}) + offset += length + ring + end + share = stats.agent_share + parts = [heading("Agents and people", "while tickets were being worked on")] + parts += rings + parts << (%(#{share}%)) + parts << %(agents) + totals.each_with_index do |(phase, seconds), index| + top = 100 + (index * 30) + percent = (seconds * 100.0 / sum).round + parts << %() + parts << %(#{esc(Statistics::PHASES[phase])}) + parts << (%(#{Statistics.duration(seconds)})) + parts << %(#{percent}%) + end + svg(width, height, parts.join("\n"), title: "Time split between agents and people") + end + + # Every acceptance criterion's result in one bar. + def proof(rows) + return if rows.empty? + + width = 760 + height = 104 + counts = STATUSES.to_h { |status| [status, rows.count { |row| row.status == status }] } + passed = counts["passed"] + color = if passed == rows.size then COLORS["passed"] + elsif counts["failed"].positive? then COLORS["failed"] + else INK + end + parts = [%() + + %(#{passed} of #{rows.size} acceptance criteria proven)] + left = 20.0 + span = width - 40.0 + parts << %() + segments = counts.filter_map do |status, count| + next if count.zero? + + length = span * count / rows.size + bar = %() + + %(#{count} #{status}) + left += length + bar + end + parts << %(#{segments.join}) + shown = counts.reject { |_, count| count.zero? } + parts << legend(shown.map { |status, count| ["#{count} #{status}", COLORS[status]] }, 20, 90) + svg(width, height, parts.join("\n"), title: "#{passed} of #{rows.size} acceptance criteria proven") + end + + def svg(width, height, body, title:) + <<~SVG + + #{esc(title)} + + #{body} + + SVG + end + + def heading(text, note) + %(#{esc(text)}) + + %(#{esc(note)}) + end + + def legend(items, left, top) + x = left + items.map do |label, color| + item = %() + + %(#{esc(label)}) + x += (label.length * 6.6) + 40 + item + end.join + end + + def scale_time(from, to, left, right) + start = from.to_f + length = [to.to_f - start, 1].max + ->(time) { left + ((time.to_f - start) / length * (right - left)) } + end + + # Round values up the axis: 0, 10, 20, 30, 40 rather than 0, 11, 21, 32, 42. + def value_grid(top, y, left, right) + step = [1, 2, 5, 10, 20, 25, 50, 100, 200, 500].find { |size| top / size <= 5 } || (top / 5.0).ceil + (0..top).step(step).map do |value| + %() + + %(#{value}) + end.join + end + + # Clock ticks at a round interval, labelled in the plan's own time zone. + def time_axis(from, to, x, bottom, top) + length = to.to_f - from.to_f + step = TICKS.find { |seconds| length / seconds <= 7 } || TICKS.last + format = step >= 86_400 || length > 86_400 ? "%-d %b" : "%H:%M" + first = (from.to_f / step).ceil * step + (first..to.to_f).step(step).map do |seconds| + time = local(seconds, from) + %() + + %() + + %(#{time.strftime(format)}) + end.join + end + + # A whole number of seconds as a time in the same zone as `like`, without float drift. + def local(seconds, like) + time = Time.at(seconds) + like.respond_to?(:time_zone) ? time.in_time_zone(like.time_zone) : time.getlocal(like.utc_offset) + end + + def step_series(points, to, x, y, color, fill: false) + path = "M#{f(x[points.first.at])},#{f(y[points.first.value])}" + points.drop(1).each { |point| path << " H#{f(x[point.at])} V#{f(y[point.value])}" } + path << " H#{f(x[to])}" + area = "" + area = %() if fill + %(#{area}) + end + + # One dot per evidence run, red when it failed, with the count on the last one. + def run_dots(points, x, y) + points.each_with_index.map do |point, index| + color = point.status == "passed" ? COLORS["passed"] : COLORS["failed"] + label = if index == points.size - 1 + %(#{point.value} proven) + end + %(Evidence #{point.status}: #{point.value} proven#{label}) + end.join + end + + def ticket_row(row, top, x, left) + ticket = row.ticket + label = "#{ticket.key} #{ticket.title.to_s.truncate(24)}" + bars = row.segments.map do |segment| + start = x[segment.from] + length = [x[segment.to] - start, 2].max + %() + + %(#{esc(ticket.key)} · #{esc(Statistics::PHASES[segment.phase])} · ) + + %(#{Statistics.duration(segment.seconds)}) + end + finish = x[row.segments.last.to] + total = row.merged? ? Statistics.duration(row.cycle_time) : "open" + rounds = row.review_rounds.positive? ? " · #{row.review_rounds} fix" : "" + %(#{esc(label)}) + + bars.join + %(#{esc(total + rounds)}) + end + + def f(number) + number.to_f.round(1).to_s.delete_suffix(".0") + end + + def esc(text) + CGI.escapeHTML(text.to_s) + end + end +end diff --git a/lib/plan_driven/cli.rb b/lib/plan_driven/cli.rb index cdc78ec..3863162 100644 --- a/lib/plan_driven/cli.rb +++ b/lib/plan_driven/cli.rb @@ -41,6 +41,7 @@ class CLI "report" => ["PLAN", "Write the delivery report"], "log" => ["PLAN", "The audit trail"], "usage" => ["PLAN", "Tokens and cost per step and per agent run"], + "stats" => ["PLAN", "Where the time went: phases, agents and people, each ticket"], "questions" => ["", "The interview's questions, with the team's changes"], "question" => ["KEY", "Change or add a question (--title, --ask, --group, --required, --optional, --remove)"], "configure" => ["", "Store API keys in ~/.plan_driven/config"], diff --git a/lib/plan_driven/cli/ticket_commands.rb b/lib/plan_driven/cli/ticket_commands.rb index 2896a2d..321b69d 100644 --- a/lib/plan_driven/cli/ticket_commands.rb +++ b/lib/plan_driven/cli/ticket_commands.rb @@ -143,6 +143,26 @@ def cmd_usage(reference = nil) ui.muted "No price for #{totals[:unpriced].join(", ")}; set config.token_prices to see dollars." end + def cmd_stats(reference = nil) + plan = find_plan(reference) + stats = Statistics.new(plan) + duration = ->(seconds) { Statistics.duration(seconds) } + ui.heading "#{plan.key} #{plan.title}: statistics" + stats.phases.each { |label, seconds| ui.say " #{label.ljust(22)}#{seconds ? duration[seconds] : "not yet"}" } + return ui.muted("Ticket statistics start when the tickets are approved.") unless stats.started? + + show_summary(stats.summary) + show_time_split(stats) + ui.say + ui.table(%w[# Est Queued Agent Review Fixes Merge Rounds Total], stats.tickets.map do |row| + [row.ticket.key, row.ticket.estimate.to_s, + *%w[queued agent review fixes merge].map do |phase| + row.seconds(phase).positive? ? duration[row.seconds(phase)] : "-" + end, + row.review_rounds.to_s, row.merged? ? duration[row.cycle_time] : row.ticket.status.tr("_", " ")] + end) + end + def cmd_report(reference = nil) plan = find_plan(reference) paths = delivery.report(plan) @@ -152,6 +172,27 @@ def cmd_report(reference = nil) private + def show_summary(summary) + ui.say " #{"Idea to delivery".ljust(22)}#{Statistics.duration(summary[:lead_time])}" + ui.say " #{"Tickets merged".ljust(22)}#{summary[:merged]} of #{summary[:tickets]}, " \ + "#{summary[:first_time]} approved the first time" + proven = "#{summary[:proven]} of #{summary[:criteria]} acceptance criteria proven" + summary[:proven] == summary[:criteria] ? ui.success(proven) : ui.warn(proven) + end + + def show_time_split(stats) + work = stats.work_seconds + return if work.zero? + + ui.say + ui.say "Where the time went while tickets were worked on (agents #{stats.agent_share}%):" + stats.totals.slice(*Statistics::WORK).each do |phase, seconds| + share = seconds * 100.0 / work + ui.say " #{Statistics::PHASES[phase].ljust(22)}#{Statistics.duration(seconds).rjust(10)} " \ + "#{"█" * (share / 4).ceil} #{share.round}%" + end + end + def explain_waiting(plan) running = plan.tickets.count(&:active_agent?) if plan.tickets.any?(&:ready?) && running >= PlanDriven.configuration.max_parallel_agents diff --git a/lib/plan_driven/evidence.rb b/lib/plan_driven/evidence.rb index e5dc551..adfcd53 100644 --- a/lib/plan_driven/evidence.rb +++ b/lib/plan_driven/evidence.rb @@ -21,6 +21,9 @@ def status # when plan-driven itself was started from a development server (the wizard). CUCUMBER_ENV = { "RAILS_ENV" => "test", "RACK_ENV" => "test" }.freeze + # Shown before each result in the Markdown report, so it reads at a glance on GitHub too. + MARKS = { "passed" => "✅", "failed" => "❌", "not run" => "⏸️", "no scenario" => "⚠️" }.freeze + module_function def tag_expression(plan) @@ -76,8 +79,8 @@ def scenario_status(element) "not run" end - def matrix(plan) - scenarios = plan.evidence_runs.last&.scenarios || [] + def matrix(plan, run = plan.evidence_runs.last) + scenarios = run&.scenarios || [] plan.tickets.flat_map do |ticket| ticket.criteria.each_with_index.map do |criterion, index| matching = scenarios.select do |scenario| @@ -94,7 +97,7 @@ def matrix_markdown(plan) rows = matrix(plan).map do |row| scenario = row.scenarios.map { |s| "#{s["name"]} (`#{s["file"]}`)" }.join("; ").presence || "-" - ["#{row.ticket.key}.#{row.number}", row.criterion, scenario, row.status] + ["#{row.ticket.key}.#{row.number}", row.criterion, scenario, "#{MARKS[row.status]} #{row.status}"] end commit = run.commit_sha.present? ? " on commit `#{run.commit_sha[0, 7]}`" : "" intro = "Cucumber, run #{run.created_at.strftime("%-d %b %Y %H:%M")}#{commit}: `#{run.command}`" diff --git a/lib/plan_driven/renderer.rb b/lib/plan_driven/renderer.rb index e47ed60..40187f9 100644 --- a/lib/plan_driven/renderer.rb +++ b/lib/plan_driven/renderer.rb @@ -17,23 +17,30 @@ def write_plan(plan, config: PlanDriven.configuration) write(plan, "plan", Markdown.plan(plan, config: config), title: "#{plan.key} #{plan.title}", config: config) end + # The charts are SVG files beside the report, so GitHub shows them in the Markdown; the HTML + # and the PDF carry them inline. def write_report(plan, config: PlanDriven.configuration) - write(plan, "delivery-report", Markdown.report(plan), - title: "#{plan.key} delivery report", config: config) + charts = Charts.report(plan) + dir = directory(plan, config: config) + FileUtils.mkdir_p(dir) + Dir[dir.join("statistics-*.svg")].each { |file| File.delete(file) } + charts.each { |name, svg| File.write(dir.join(name), svg) } + write(plan, "delivery-report", Markdown.report(plan, charts: charts.keys), + title: "#{plan.key} delivery report", config: config, images: charts) end def directory(plan, config: PlanDriven.configuration) config.docs_root.join(plan.slug) end - def write(plan, name, markdown, title:, config:) + def write(plan, name, markdown, title:, config:, images: {}) dir = directory(plan, config: config) FileUtils.mkdir_p(dir) md = dir.join("#{name}.md") html = dir.join("#{name}.html") pdf = dir.join("#{name}.pdf") File.write(md, markdown) - File.write(html, HTML.document(markdown, title: title)) + File.write(html, HTML.document(markdown, title: title, images: images)) written = PDF.render(html, pdf, config: config) { markdown: md, html: html, pdf: written ? pdf : nil } end diff --git a/lib/plan_driven/renderer/html.rb b/lib/plan_driven/renderer/html.rb index 082e1f2..2195511 100644 --- a/lib/plan_driven/renderer/html.rb +++ b/lib/plan_driven/renderer/html.rb @@ -7,10 +7,14 @@ module Renderer # and doesn't need to be. module HTML STYLE = File.read(File.expand_path("style.css", __dir__)) + IMAGE = /\A!\[([^\]]*)\]\(([^)\s]+)\)\z/ + # A table cell that is only a result becomes a coloured pill, and colours its row. + RESULT = /\A(?:#{Evidence::MARKS.values.map { |mark| Regexp.escape(mark) }.join("|")})?\s* + (passed|failed|not\ run|no\ scenario|merged)\z/x module_function - def document(markdown, title:) + def document(markdown, title:, images: {}) <<~HTML @@ -21,19 +25,22 @@ def document(markdown, title:)
    - #{convert(markdown)} + #{convert(markdown, images: images)}
    HTML end - def convert(markdown) + def convert(markdown, images: {}) lines = markdown.to_s.lines.map(&:chomp) out = [] until lines.empty? line = lines.first - if line.start_with?("```") + if (image = line.strip.match(IMAGE)) + lines.shift + out << figure(image[1], image[2], images) + elsif line.start_with?("```") out << code_block(lines) elsif line.match?(/\A\s*\|/) out << table(take_while(lines) { |l| l.match?(/\A\s*\|/) }) @@ -72,10 +79,32 @@ def table(rows) header, *body = cells body = body.reject { |row| row.all? { |cell| cell.match?(/\A:?-+:?\z/) } } head = header.map { |cell| "#{inline(cell)}" }.join - rows = body.map { |row| "#{row.map { |cell| "#{inline(cell.gsub("\\|", "|"))}" }.join}" } + rows = body.map { |row| table_row(row) } "#{head}#{rows.join}
    " end + def table_row(row) + results = row.filter_map { |cell| cell.match(RESULT)&.[](1) } + cells = row.map do |cell| + result = cell.match(RESULT)&.[](1) + content = if result + %(#{result}) + else + inline(cell.gsub("\\|", "|")) + end + "#{content}" + end + klass = results.last ? %( class="#{results.last.tr(" ", "-")}") : "" + "#{cells.join}" + end + + # A chart written next to the document is inlined, so the HTML and PDF stand alone. + def figure(alt, src, images) + body = images[src] || %(#{CGI.escapeHTML(alt)}) + %(
    #{body}
    ) + end + def list(lines) ordered = lines.first.match?(/\A\s*\d+\./) items = [] diff --git a/lib/plan_driven/renderer/markdown.rb b/lib/plan_driven/renderer/markdown.rb index 1fdf11d..3aa908f 100644 --- a/lib/plan_driven/renderer/markdown.rb +++ b/lib/plan_driven/renderer/markdown.rb @@ -17,10 +17,12 @@ def plan(plan, config: PlanDriven.configuration) "#{parts.join("\n\n")}\n" end - def report(plan) + # `charts` are the SVG files written next to the report, by name. + def report(plan, charts: []) parts = ["# #{plan.key}: #{plan.title} (delivery report)", meta(plan)] - parts << "## Summary\n\n#{summary(plan)}" + parts << "## Summary\n\n#{summary(plan)}#{chart(charts, "statistics-proof.svg", "Acceptance criteria proven")}" parts << "## Tickets and pull requests\n\n#{delivery_table(plan)}" + parts << "## Statistics\n\n#{statistics(plan, charts)}" parts << "## Acceptance criteria and proof\n\n#{Evidence.matrix_markdown(plan)}" parts << "## Checks run on each pull request\n\n#{guard_findings(plan)}" parts << "## Tokens and cost\n\n#{usage_table(plan)}" @@ -89,6 +91,43 @@ def delivery_table(plan) table(["#", "Ticket", "Status", "Pull request", "Merge commit", "Approved by"], rows) end + def statistics(plan, charts) + stats = Statistics.new(plan) + return "Statistics start when the tickets are approved." unless stats.started? + + figures = [["statistics-burnup.svg", "Acceptance criteria merged and proven"], + ["statistics-timeline.svg", "Where the time went, ticket by ticket"], + ["statistics-time.svg", "Agents and people"]].map { |name, alt| chart(charts, name, alt) }.join + "#{table(%w[Measure Value], statistics_rows(stats))}#{figures}\n\n#{ticket_times(stats)}" + end + + def statistics_rows(stats) + s = stats.summary + duration = ->(seconds) { Statistics.duration(seconds) } + rows = stats.phases.filter_map { |label, seconds| ["#{label} time", duration[seconds]] if seconds } + rows << ["Idea to delivery", duration[s[:lead_time]]] + rows << ["Pull requests approved the first time", "#{s[:first_time]} of #{s[:merged]}"] + rows << ["Review rounds (feedback sent to an agent)", s[:review_rounds].to_s] + rows << ["Agents' share of the time tickets were worked on", "#{s[:agent_share]}%"] if s[:agent_share] + rows << ["Estimated points", s[:points].to_s] + rows + end + + def ticket_times(stats) + duration = ->(seconds) { seconds.positive? ? Statistics.duration(seconds) : "-" } + rows = stats.tickets.map do |row| + [row.ticket.key, row.ticket.estimate.to_s, duration[row.seconds("queued")], duration[row.seconds("agent")], + duration[row.seconds("review")], duration[row.seconds("fixes")], duration[row.seconds("merge")], + row.review_rounds.to_s, row.merged? ? Statistics.duration(row.cycle_time) : "open"] + end + table(["#", "Estimate", "Queued", "Agent coding", "Waiting for review", "Fixing feedback", + "Approved, not merged", "Review rounds", "Start to merge"], rows) + end + + def chart(charts, name, alt) + charts.include?(name) ? "\n\n![#{alt}](#{name})" : "" + end + def guard_findings(plan) lines = plan.tickets.map do |ticket| report = Guards::Report.from_h(ticket.guard_report) diff --git a/lib/plan_driven/renderer/style.css b/lib/plan_driven/renderer/style.css index 542291a..5874865 100644 --- a/lib/plan_driven/renderer/style.css +++ b/lib/plan_driven/renderer/style.css @@ -20,3 +20,24 @@ th { background: #f6f8fa; font-weight: 600; } tr { break-inside: avoid; } a { color: #0969da; text-decoration: none; } h1, h2, h3 { break-after: avoid; } +html { -webkit-print-color-adjust: exact; print-color-adjust: exact; } +h2 { color: #1f2330; border-left: 4px solid #cc342d; padding-left: 10px; } +th { background: #f3f4f6; } +.result { display: inline-block; padding: 1px 9px; border-radius: 10px; font-size: 8.5pt; font-weight: 600; white-space: nowrap; } +.result::before { margin-right: 4px; } +.result.passed, .result.merged { background: #dcfce7; color: #15803d; } +.result.passed::before, .result.merged::before { content: "✓"; } +.result.failed { background: #fee2e2; color: #b91c1c; } +.result.failed::before { content: "✗"; } +.result.not-run { background: #fef3c7; color: #b45309; } +.result.not-run::before { content: "•"; } +.result.no-scenario { background: #f3f4f6; color: #6b7280; } +.result.no-scenario::before { content: "–"; } +tr.passed td:first-child { border-left: 3px solid #16a34a; } +tr.failed td { background: #fef2f2; } +tr.failed td:first-child { border-left: 3px solid #dc2626; } +tr.not-run td { background: #fffbeb; } +tr.not-run td:first-child { border-left: 3px solid #f59e0b; } +tr.no-scenario td:first-child { border-left: 3px solid #9ca3af; } +figure.chart { margin: 12px 0 18px; border: 1px solid #e5e7eb; border-radius: 10px; overflow: hidden; break-inside: avoid; } +figure.chart svg, figure.chart img { display: block; width: 100%; height: auto; } diff --git a/lib/plan_driven/statistics.rb b/lib/plan_driven/statistics.rb new file mode 100644 index 0000000..93b4485 --- /dev/null +++ b/lib/plan_driven/statistics.rb @@ -0,0 +1,195 @@ +# frozen_string_literal: true + +module PlanDriven + # Where a plan's time went, read from its audit trail: when each ticket was queued, when an + # agent was writing code, when it waited for a person, and when its acceptance criteria were + # merged and then proven. Arithmetic on recorded events, so it gives the same answer every time. + class Statistics + PHASES = { + "queued" => "Queued", + "agent" => "Agent coding", + "review" => "Waiting for review", + "fixes" => "Agent fixing feedback", + "merge" => "Approved, not merged" + }.freeze + WORK = %w[agent review fixes merge].freeze + AGENT = %w[agent fixes].freeze + + # Each of these events starts the ticket's next phase; merging ends the last one. + NEXT_PHASE = { + "ticket.agent_started" => "agent", "ticket.pr_opened" => "review", "ticket.agent_failed" => "review", + "ticket.changes_requested" => "fixes", "ticket.pr_approved" => "merge", "ticket.merged" => nil + }.freeze + + Segment = Struct.new(:phase, :from, :to) do + def seconds = to - from + end + + TicketRow = Struct.new(:ticket, :segments, :review_rounds, :merged_at, keyword_init: true) do + def seconds(phase = nil) + segments.select { |segment| phase.nil? || segment.phase == phase }.sum(&:seconds) + end + + def merged? = !merged_at.nil? + def first_time? = merged? && review_rounds.zero? + def started_at = segments.find { |segment| segment.phase != "queued" }&.from + def cycle_time = merged_at && started_at && (merged_at - started_at) + end + + Point = Struct.new(:at, :value, :status) + + attr_reader :plan, :now + + def self.duration(seconds) + return "-" if seconds.nil? + + seconds = seconds.round + return "#{seconds}s" if seconds < 60 + + minutes = seconds / 60 + return "#{minutes} min" if minutes < 60 + + hours, minutes = minutes.divmod(60) + return "#{hours} h#{" #{minutes} min" if minutes.positive?}" if hours < 24 + + days, hours = hours.divmod(24) + "#{days} d#{" #{hours} h" if hours.positive?}" + end + + def initialize(plan, now: Time.now) + @plan = plan + @now = now + @events = plan.events.includes(:ticket).to_a + end + + def started? = !development_start.nil? + + def development_start + @development_start ||= (first("tickets.approved") || first("ticket.agent_started"))&.created_at + end + + def delivered_at + first("plan.delivered")&.created_at + end + + # The span the charts draw: from approving the tickets to delivery, or to now while it runs. + def window + return unless started? + + finish = [delivered_at || now, *plan.evidence_runs.map(&:created_at)].max + [development_start, [finish, development_start + 60].max] + end + + def tickets + @tickets ||= plan.tickets.map { |ticket| ticket_row(ticket) } + end + + def totals + PHASES.keys.to_h { |phase| [phase, tickets.sum { |row| row.seconds(phase) }] } + end + + def work_seconds + totals.slice(*WORK).values.sum + end + + # The agents' part of the time a ticket was being worked on, from 0 to 100. + def agent_share + work = work_seconds + return if work.zero? + + (totals.slice(*AGENT).values.sum * 100.0 / work).round + end + + # Planning phases, first to last, as [label, seconds]. + def phases + drafted = first("plan.drafted")&.created_at + approved = last("plan.approved")&.created_at + proven = plan.evidence_runs.find(&:passed?)&.created_at + [["Planning", span(drafted, approved)], ["Tickets", span(approved, development_start)], + ["Development", span(development_start, delivered_at || (now if started?))], + ["Proof", span(delivered_at, proven)]] + end + + # Criteria merged and criteria proven by a passing test, over time, against the plan's scope. + def burnup + return unless started? + + { scope: plan.tickets.sum { |ticket| ticket.criteria.size }, from: window.first, to: window.last, + merged: merged_points, proven: proven_points } + end + + def summary + rows = tickets + { lead_time: span(first("plan.drafted")&.created_at, delivered_at || now), development: phases[2].last, + merged: rows.count(&:merged?), tickets: rows.size, first_time: rows.count(&:first_time?), + review_rounds: rows.sum(&:review_rounds), agent_share: agent_share, + points: plan.tickets.sum { |ticket| ticket.estimate.to_i } }.merge(proof, usage) + end + + private + + def proof + matrix = Evidence.matrix(plan) + { proven: matrix.count { |row| row.status == "passed" }, criteria: matrix.size, + evidence: plan.evidence_runs.any? } + end + + def usage + totals = Usage.totals(Usage.rows(plan)) + { tokens: totals[:total_tokens], cost: totals[:cost] } + end + + def ticket_row(ticket) + events = @events.select { |event| event.ticket_id == ticket.id && NEXT_PHASE.key?(event.name) } + TicketRow.new(ticket: ticket, segments: segments(events), + review_rounds: events.count { |event| event.name == "ticket.changes_requested" }, + merged_at: events.reverse.find { |event| event.name == "ticket.merged" }&.created_at) + end + + # Every ticket is queued from the moment the tickets are approved until its agent starts. + def segments(events) + return [] unless development_start + + phase = "queued" + from = development_start + list = events.filter_map do |event| + segment = Segment.new(phase, from, event.created_at) if phase && event.created_at > from + phase = NEXT_PHASE[event.name] + from = [from, event.created_at].max + segment + end + finish = delivered_at || now + list << Segment.new(phase, from, finish) if phase && finish > from + list + end + + def merged_points + seen = Set.new + count = 0 + merges = @events.select { |event| event.name == "ticket.merged" && event.ticket && seen.add?(event.ticket_id) } + [Point.new(development_start, 0)] + merges.map do |event| + count += event.ticket.criteria.size + Point.new(event.created_at, count) + end + end + + def proven_points + runs = plan.evidence_runs.to_a + [Point.new(development_start, 0)] + runs.map do |run| + Point.new(run.created_at, Evidence.matrix(plan, run).count { |row| row.status == "passed" }, run.status) + end + end + + def first(name) + @events.find { |event| event.name == name } + end + + def last(name) + @events.reverse.find { |event| event.name == name } + end + + def span(from, to) + from && to && to >= from ? to - from : nil + end + end +end diff --git a/lib/plan_driven/wizard.rb b/lib/plan_driven/wizard.rb index 155a976..bc04ee2 100644 --- a/lib/plan_driven/wizard.rb +++ b/lib/plan_driven/wizard.rb @@ -14,7 +14,7 @@ module Wizard # The commands the wizard may run, built from form fields. Nothing else reaches a shell: # arguments are passed as an array, never interpolated. module Commands - PLAN_ONLY = %w[check submit pdf status evidence report usage log].freeze + PLAN_ONLY = %w[check submit pdf status evidence report usage stats log].freeze BUILDERS = { "doctor" => ->(_p) { [] }, diff --git a/spec/plan_driven/statistics_spec.rb b/spec/plan_driven/statistics_spec.rb new file mode 100644 index 0000000..21161bc --- /dev/null +++ b/spec/plan_driven/statistics_spec.rb @@ -0,0 +1,114 @@ +# frozen_string_literal: true + +RSpec.describe PlanDriven::Statistics do + let(:plan) { create_ticketed_plan(status: "delivered", ticket_status: "merged") } + let(:start) { Time.utc(2026, 9, 30, 13, 0, 0) } + let(:stats) { described_class.new(plan, now: start + 3600) } + + def log(name, minute, ticket: nil) + plan.events.create!(name: name, actor: "Ada", ticket: ticket && plan.ticket!(ticket), + created_at: start + (minute * 60)) + end + + # T1 gets feedback once; T2 goes through first time; the rest merged without events. + before do + log("plan.drafted", -30) + log("plan.approved", -20) + log("tickets.approved", 0) + [["ticket.agent_started", 1], ["ticket.pr_opened", 11], ["ticket.changes_requested", 15], + ["ticket.pr_opened", 20], ["ticket.pr_approved", 22], ["ticket.merged", 23]].each { |name, at| log(name, at, ticket: "T1") } + [["ticket.agent_started", 23], ["ticket.pr_opened", 30], ["ticket.pr_approved", 40], + ["ticket.merged", 41]].each { |name, at| log(name, at, ticket: "T2") } + log("plan.delivered", 41) + end + + def minutes(row, phase) + row.seconds(phase) / 60 + end + + it "formats durations the way people say them" do + expect([45, 600, (3 * 3600) + 2400, 26 * 3600, nil].map { |s| described_class.duration(s) }) + .to eq(["45s", "10 min", "3 h 40 min", "1 d 2 h", "-"]) + end + + it "splits each ticket's time into queued, agent, review, fixes and merge" do + t1, t2 = stats.tickets.first(2) + expect(%w[queued agent review fixes merge].map { |phase| minutes(t1, phase) }).to eq([1, 10, 6, 5, 1]) + expect(%w[queued agent review fixes merge].map { |phase| minutes(t2, phase) }).to eq([23, 7, 10, 0, 1]) + expect([t1.review_rounds, t1.first_time?, t2.first_time?]).to eq([1, false, true]) + expect(t1.cycle_time / 60).to eq(22) + end + + it "ends an unfinished segment at delivery, not at the time it's read" do + expect(stats.tickets.last.segments.map { |segment| [segment.phase, segment.seconds / 60] }).to eq([["queued", 41]]) + end + + it "totals the work and the agents' share of it" do + expect(stats.totals.transform_values { |seconds| seconds / 60 }.slice(*described_class::WORK)) + .to eq("agent" => 17, "review" => 16, "fixes" => 5, "merge" => 2) + expect(stats.agent_share).to eq(55) + end + + it "times the phases from planning to proof" do + expect(stats.phases.map { |label, seconds| [label, seconds && (seconds / 60)] }) + .to eq([["Planning", 10], ["Tickets", 20], ["Development", 41], ["Proof", nil]]) + end + + it "burns up criteria as tickets merge and as evidence proves them" do + t1 = plan.ticket!("T1") + PlanDriven::Evidence.record(plan, cucumber_json([{ feature_tag: t1.feature_tag, tags: ["@ac-1"] }]), + command: "cucumber", actor: "ci") + data = stats.burnup + sizes = plan.tickets.first(2).map { |ticket| ticket.criteria.size } + expect(data[:merged].map(&:value)).to eq([0, sizes[0], sizes.sum]) + expect(data[:proven].map(&:value)).to eq([0, 1]) + expect(data[:scope]).to eq(plan.tickets.sum { |ticket| ticket.criteria.size }) + end + + it "has nothing to chart before the tickets are approved" do + fresh = create_plan + expect(described_class.new(fresh).started?).to be(false) + expect(PlanDriven::Charts.report(fresh).keys).to eq([]) + end + + describe "charts and the delivery report" do + before do + t1 = plan.ticket!("T1") + json = cucumber_json([{ feature_tag: t1.feature_tag, tags: ["@ac-1"] }, + { feature_tag: t1.feature_tag, tags: ["@ac-2"], status: "failed" }]) + PlanDriven::Evidence.record(plan, json, command: "cucumber", actor: "ci") + end + + it "draws every chart as standalone SVG" do + charts = PlanDriven::Charts.report(plan, stats: stats) + expect(charts.keys).to eq(%w[statistics-proof.svg statistics-burnup.svg statistics-timeline.svg + statistics-time.svg]) + expect(charts.values).to all(start_with('55%<") + expect(charts["statistics-proof.svg"]).to include("1 of 7 acceptance criteria proven", "1 failed") + end + + it "writes the charts beside the report and inlines them in the HTML, with coloured results" do + paths = PlanDriven::Renderer.write_report(plan) + dir = paths[:markdown].dirname + markdown = paths[:markdown].read + html = paths[:html].read + + expect(dir.children.map { |file| file.basename.to_s }.grep(/statistics-/).sort) + .to eq(%w[statistics-burnup.svg statistics-proof.svg statistics-time.svg statistics-timeline.svg]) + expect(markdown).to include("## Statistics", "![Where the time went, ticket by ticket](statistics-timeline.svg)", + "| T1.1 |", "✅ passed", "❌ failed", "⚠️ no scenario", "| Review rounds") + expect(html).to include('
    ', + '
    passed') + expect(html).not_to include(" ["What is too short"], "passes" => ["Who is set"] }) plan.tickets.create!(key: "T1", title: "Migration: Create categories", status: "pr_open", pr_url: "https://x/pr/1", pr_number: 1, acceptance_criteria: ["categories exist"]) +plan.log!("tickets.approved", actor: "Ada") +plan.log!("ticket.agent_started", actor: "Ada", ticket: plan.tickets.first) +plan.log!("ticket.pr_opened", actor: "cursor-agent", ticket: plan.tickets.first) app = Rack::MockRequest.new(Rails.application) local = { "REMOTE_ADDR" => "127.0.0.1" } @@ -48,7 +51,9 @@ class WizardApp < Rails::Application "/plan_driven/plans/PD-1/approve" => ["review", "submit it on the Plan step"], "/plan_driven/plans/PD-1/tickets" => ["Migration: Create categories", "categories exist"], "/plan_driven/plans/PD-1/agents" => ["PR #1", "Approve PR"], - "/plan_driven/plans/PD-1/finish" => ["Write the delivery report"], + "/plan_driven/plans/PD-1/finish" => ["Write the delivery report", "Open the statistics"], + "/plan_driven/plans/PD-1/statistics" => ["Where the time went", "Ticket by ticket", "Print in the terminal", + "0 of 1 acceptance criteria proven"], "/plan_driven/jobs/0000000000000000" => ["no job"] } checks.each do |path, texts|