From 80f4127a0a5f2163f64da6643b23a96d96cf2acc Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 11:12:55 -0300 Subject: [PATCH 1/9] feat(hyperfleet-jira): make the sprint commands script-driven /sprint-status and /sprint-pulse-check read their numbers from scripts/sprint_status.py and scripts/pulse_check.py instead of hand-written JQL, which cannot see story points and silently drops issues past the 100-issue page. Movement is now the most recent of the exact status change, the last human comment and the assignment to the current owner, read from the Jira changelog. Automation comments do not count, and a New to Backlog sweep is a reclassification, not movement. The pulse check emits a nudge queue with one row per item. Its Ask starts with a verb from a closed set and follows the item's state: blocked work names the blocker, Review asks for a decision, a spike asks for a decision note, and unstarted work asks for a date. Both commands render text/markdown output and ship unit tests. --- AGENTS.md | 2 +- hyperfleet-jira/.claude-plugin/plugin.json | 2 +- hyperfleet-jira/.gitignore | 2 + hyperfleet-jira/README.md | 24 +- .../commands/sprint-pulse-check.md | 126 ++ hyperfleet-jira/commands/sprint-status.md | 149 ++- hyperfleet-jira/scripts/pulse_check.py | 649 ++++++++++ hyperfleet-jira/scripts/sprint_status.py | 1044 +++++++++++++++++ hyperfleet-jira/tests/test_pulse_check.py | 447 +++++++ hyperfleet-jira/tests/test_sprint_status.py | 341 ++++++ 10 files changed, 2730 insertions(+), 56 deletions(-) create mode 100644 hyperfleet-jira/.gitignore create mode 100644 hyperfleet-jira/commands/sprint-pulse-check.md create mode 100755 hyperfleet-jira/scripts/pulse_check.py create mode 100755 hyperfleet-jira/scripts/sprint_status.py create mode 100644 hyperfleet-jira/tests/test_pulse_check.py create mode 100644 hyperfleet-jira/tests/test_sprint_status.py diff --git a/AGENTS.md b/AGENTS.md index 028a082..c4c5d83 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,7 +30,7 @@ Before making any changes: | Plugin | Skills | Commands | Agents | Hooks | Version | |--------|:------:|:--------:|:------:|:-----:|---------| | `hyperfleet-code-review` | 2 (`review-pr`, `review-local`) | - | - | - | 0.8.1 | -| `hyperfleet-jira` | 4 | 6 | - | - | 0.7.0 | +| `hyperfleet-jira` | 4 | 7 | - | - | 0.8.0 | | `hyperfleet-architecture` | 1 | - | - | - | 0.2.0 | | `hyperfleet-standards` | 1 | - | - | - | 1.1.0 | | `hyperfleet-operational-readiness` | 1 | - | - | - | 0.2.0 | diff --git a/hyperfleet-jira/.claude-plugin/plugin.json b/hyperfleet-jira/.claude-plugin/plugin.json index 600b0e3..1bc8004 100644 --- a/hyperfleet-jira/.claude-plugin/plugin.json +++ b/hyperfleet-jira/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "hyperfleet-jira", - "version": "0.7.0", + "version": "0.8.0", "description": "JIRA integration for HyperFleet team - sprint management, task tracking, ticket creation, triage, and story point estimation", "author": { "name": "Ciaran Roche", diff --git a/hyperfleet-jira/.gitignore b/hyperfleet-jira/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/hyperfleet-jira/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/hyperfleet-jira/README.md b/hyperfleet-jira/README.md index d50bfa7..91cb4bd 100644 --- a/hyperfleet-jira/README.md +++ b/hyperfleet-jira/README.md @@ -11,6 +11,7 @@ A Claude Code plugin that integrates JIRA with your development workflow using [ ### For Team Leads - **`/sprint-status`** - Comprehensive sprint health overview +- **`/sprint-pulse-check`** - Twice-weekly nudge queue for large work items (5 and 8 SP) - **`/team-weekly-update`** - Weekly team progress report grouped by activity type and epic - **`/triage`** - Audit tickets for missing fields and quality issues @@ -57,6 +58,7 @@ rm -rf "jira_${VERSION#v}_linux_x86_64" "jira_${VERSION#v}_linux_x86_64.tar.gz" ```bash export JIRA_API_TOKEN="your-api-token" ``` + The collector scripts also use this token for the Jira REST API, because jira-cli does not expose the changelog. The changelog carries the exact status transition and the assignee change. Without it, movement falls back to the status category date and comments only, so an item can look older than it is. 3. **Initialize jira-cli for HyperFleet:** ```bash @@ -122,10 +124,24 @@ Comprehensive sprint health report: /sprint-status HF # Specific project ``` Output includes: -- Progress by status and story points -- Blockers and at-risk items -- Team workload distribution -- Carry-over risk assessment +- Progress by status, by story points and by item count +- Blocked items, highest-priority open items, and stale in-progress work +- Team workload distribution, including unassigned work +- Carry-over candidates and a capacity projection from the previous sprint's pace + +The numbers come from `scripts/sprint_status.py` (`--format json` or the rendered `--format markdown`), not from hand-written JQL: story points need `issue view --raw`, and `issue list` truncates at 100 issues without saying so. + +#### `/sprint-pulse-check` (Team Leads) +Nudge queue for the large items, run a couple of times per week: +``` +/sprint-pulse-check +/sprint-pulse-check HF # Specific project +``` +Output includes: +- Items >= 5 SP ranked by days without movement (last status change, last human comment, or assignment to the current owner) +- The specific ask per item, pointing at the blocker or the reviewer when the delay is not the owner's +- Assignment gap: large items with no owner, and which of them block other work +- Concentration: owners holding more than one large item #### `/team-weekly-update` (Team Leads) Weekly progress report for team updates: diff --git a/hyperfleet-jira/commands/sprint-pulse-check.md b/hyperfleet-jira/commands/sprint-pulse-check.md new file mode 100644 index 0000000..36cd786 --- /dev/null +++ b/hyperfleet-jira/commands/sprint-pulse-check.md @@ -0,0 +1,126 @@ +--- +description: Pulse check on large work items (5 and 8 SP) - the nudge queue leads work through twice a week +allowed-tools: Bash +argument-hint: [project-key] +--- + +# Sprint Pulse Check + +Leads run a pulse check a couple of times per week during a sprint on the large items (5 and 8 SP), to find out whether the owner needs help or has open questions. The agreement behind it: work over 5 story points needs shared context, and a reviewer cannot reconstruct that context from a merged PR. + +This command produces a short nudge queue. It is not a sprint status report: it does not compute progress, and it does not summarize the sprint. For that, use `/sprint-status`. + +## Arguments +- `$1` (optional): Project key (e.g., HYPERFLEET). If not provided, uses HYPERFLEET as default. + +## Instructions + +1. **Locate the collector script.** It ships with this command in the plugin. No globs: an unmatched glob aborts the shell in zsh. + ```bash + PULSE="" + for root in "$CLAUDE_PLUGIN_ROOT" \ + "$HOME/.claude/plugins/cache/hyperfleet-claude-plugins/hyperfleet-jira" \ + "$HOME/.claude/plugins/marketplaces/hyperfleet-claude-plugins/hyperfleet-jira"; do + [ -n "$root" ] || continue + found=$(find "$root" -maxdepth 3 -name pulse_check.py -type f 2>/dev/null | head -1) + [ -n "$found" ] && { PULSE="$found"; break; } + done + echo "$PULSE" + ``` + If `$PULSE` is empty, stop and say so. The script is the command: do not reimplement the calculation inline. + +2. **Run it:** + ```bash + python3 "$PULSE" --project HYPERFLEET --format json + ``` + Options: `--today YYYY-MM-DD` for a reproducible run, `--format text` for a ready-to-paste block, `--min-sp` and `--max-rows` to move the thresholds, `--link-style markdown|slack|bare` to match the destination, `--next-pulse YYYY-MM-DD` to print the next scheduled pulse (omit it when the lead has not scheduled one, and the output says "to be scheduled"). + + The script reads the active sprint, the open items at or above `--min-sp`, the movement signals, and the status of every link target. It returns the queue, the escalation buckets, the assignment gap and the concentration. + +3. **Do not recompute by hand.** The script's `days_without_movement`, `open_blockers` and `assignment_gap` are the numbers of record. If a value looks wrong, fix the script. + +4. **Sharpen the ask.** Each queue item carries a default `ask` derived from the ladder. Rewrite it only when you have concrete context the script cannot have - which reviewer to pull in, which blocker just closed, which decision stalled. Keep it to one line. + +5. **Apply the courtesies the script cannot:** + - merge two rows from the same owner when the ask is identical + - never promote an item the script left out of the queue (below `--action-after` days) + - when an item is `Review`, the ask names reviewers, not the owner + - when the item is blocked, the ask names the blocker, never the person holding the ticket + +6. **Do not post comments.** This command is read-only. The lead posts the ask (or approves a draft), because a bot comment changes the very signal the next pulse check reads. + +## Escalation Ladder + +| Days without movement | Action | +|---|---| +| 0-4 | none; leave the owner alone | +| 5-9 | Slack nudge, and ask for a comment on the ticket with the open questions or the plan | +| 10+ | office hours slot; the engineer posts context, design note, or PR link on the ticket | +| 20+, or two pulses without answer | lead decides: re-assign, split the item, or drop it from the sprint | + +Two rules that come from the retro and should shape the ask: + +- **The evidence of a pulse check is a comment on the ticket,** not a Slack message. Slack does not reach the reviewer and dies at end of day, which is the exact failure the pulse check exists to prevent. +- **Nudge the reviewer when the item is in `Review`.** A large item parked in review is a review-capacity problem, not a progress problem of the owner. + +And two rules that come from running the check: + +- **Blocked time is not the owner's time.** If the item is blocked by another open ticket, the Ask points at the blocker's owner ("gated by HYPERFLEET-1669, nudge the reviewer"), or at assigning the blocker if it is unowned. Do not put the blocked delay on the person holding the item, and do not raise it to the 20-day rung. +- **Assignment resets the clock.** A ticket handed to someone last week has one week without movement, not the months it spent in Backlog before that. The script reads the assignee changes from the Jira changelog; without `JIRA_API_TOKEN` it falls back to status and comments only, so an item can look older than it is. + +## Output Format + +One screen. Slack-ready. Ticket keys are links; keys in prose stay bare. No progress bar. + +```text +Pulse check - Hyperfleet Sprint 19, 2026-11-03 +Jira: https:///browse/ + +Nudge queue (5 of 7 owned large items need action): + +| Ticket | Title | Owner | SP | Status · age | Ask | +|--------|-------|-------|----|--------------|-----| +| [HYPERFLEET-1413](https:///browse/HYPERFLEET-1413) | Verify N-1 to N operator upgrades converge the API operand | Tirth | 5 | In Progress · 20d | 20+ days in progress: dated plan on the ticket, or re-scope | +| [HYPERFLEET-1616](https:///browse/HYPERFLEET-1616) | SPIKE: Extend Prow testing to support OLM installs classic and v1 | Mallory | 5 | Backlog · 60d (since 09-04) | No start after 60d: set a start date this week or drop from Sprint 19 | + +No action: HYPERFLEET-1671 (4d, assigned 10-30), HYPERFLEET-1751 (commented yesterday) + +Assignment gap: 17 items / 85 SP have no owner +- largest: HYPERFLEET-XXXX (8 SP), HYPERFLEET-XXXX (5 SP) +- 5 SP: N items + +Concentration: Phuongnhat holds 3 of 7 owned items (21 of 41 SP) + +Movement = the most recent of the exact last status change, the last human comment and the assignment to the current owner; a New-to-Backlog reclassification is not movement. +`updated` is not used: bulk edits make untouched tickets look active. +Next pulse: 2026-11-05 +``` + +Rules for the output: + +- **Never wrap the report in a code fence for chat or TUI.** The fence in the template is illustrative: inside it the links and emphasis reach the reader as literal characters. Use the fence only when the destination is Slack, email, or a log file, and say which one you are formatting for. +- **Print the base URL once, under the title.** It is the fallback for the keys that stay bare in prose. The script emits it from the `server:` entry in `~/.config/.jira/.config.yml`; never hardcode it. +- **Ticket keys are links.** The script emits `[HYPERFLEET-XXXX](url)` by default; pass `--link-style slack` for Slack (``) and `--link-style bare` for a log or a plain-text paste. Never mix two styles in one output. +- **One table row per item, six columns, `Ask` last.** `Ticket | Title | Owner | SP | Status · age | Ask`. No second row, no empty cell: an `Ask` row under the data row squeezes the text into the first column, and Markdown has no `colspan` to fix it. `Ask` sits last because the last column is the one that grows, so a long ask wraps at the right edge instead of widening the table from the left. +- **Status and age share a column.** "Review · 12d" is one thought for the reader. Splitting it into two columns costs width and buys nothing. +- **Keep the title and the SP.** Without the title the ask loses its referent; without the SP an 8-point item gets the same nudge as a 5. +- The **Ask** names the next action, not the problem, and it starts with a verb: `Ask Martin to approve or reject HYPERFLEET-1636 (Review 7d); assign HYPERFLEET-1523`, `Ask a reviewer to approve or reject`, `Start this week or drop from the sprint`, `Post a start date and the first step on the ticket`. +- **The verb comes from a closed set:** `ask` (approve/reject, status, start or drop), `assign`, `post`, `start`, `propose` (a split), `confirm` (a date). A closed set keeps the column scannable and countable, and it bounds the hand rewrite in step 4 to the specifics - who, which PR, which blocker - never to the choice of action. +- **Never restate the item's own age in the Ask.** It is in the `Status · age` cell beside it; repeating it costs width and produces "20+ days: 20+ days". A blocker's age does appear, because that clock is not in the table. +- **The verb follows the state, not the age alone:** blocked items name the blocker's move, `Review` asks a reviewer for a decision, `In Progress` asks for evidence on the ticket, and unstarted work asks for a date; a spike asks for the decision note, never for a start date. +- Do not repeat the same owner across rows if two items have the same ask - merge them into one row. +- Items in good standing stay visible only in the single "No action" line, never as table rows. +- In the `Status · age` cell, `(assigned MM-DD)` marks a clock shortened by a reassignment and `(since MM-DD)` marks a Backlog item with no start. Never show both. +- A blocker's age is its own last workflow transition, not the blocked item's. A blocker in `Review` leads the ask and names its reviewer (`Ask Martin to approve or reject HYPERFLEET-1636 (Review 7d)`); an unowned blocker becomes `assign HYPERFLEET-1523`, because there is nobody to ask. +- State the movement definition in every output. Without it the numbers start arguments. +- Date the output, and print the next pulse date, so a stale copy is recognizable at a glance. + +## Limits + +Five things the numbers cannot tell you: + +- **Bots are not movement.** Comments from app accounts are ignored, so a ticket whose only comments come from "Automation for Jira" or a GitHub sync shows the status-change clock. That is correct for "a human moved it", and it means a synced PR does not register: check the PR before nudging. +- **Reclassification is not movement.** A bulk `New -> Backlog` sweep changes status without work, so transitions where both sides are `New` or `Backlog` are ignored. A transition inside a category, such as `In Progress -> Review`, does count. +- **`Review` measures review decisions, not effort.** Review activity lives on GitHub, so days without movement on a `Review` item means "no reviewer decided". The ask points at reviewers, not at the owner. +- **The queue is sprint-scoped.** A large item outside the sprint never appears, however stalled it is; that is `/triage` territory. +- **No memory.** The script cannot tell "nudged twice already" from "first nudge": that lives in the ticket comments, and the 20-day rung is the proxy. If the team wants a real trail, the evidence rule above is what produces it. diff --git a/hyperfleet-jira/commands/sprint-status.md b/hyperfleet-jira/commands/sprint-status.md index ac0593c..9fe1c57 100644 --- a/hyperfleet-jira/commands/sprint-status.md +++ b/hyperfleet-jira/commands/sprint-status.md @@ -13,82 +13,131 @@ Comprehensive sprint health report for team leads and scrum masters. ## Instructions -1. **Get current sprint info:** +1. **Locate the collector script.** It ships with this command in the plugin. No globs: an unmatched glob aborts the shell in zsh. ```bash - jira sprint list --current -p HYPERFLEET --plain 2>/dev/null + SPRINT="" + for root in "$CLAUDE_PLUGIN_ROOT" \ + "$HOME/.claude/plugins/cache/hyperfleet-claude-plugins/hyperfleet-jira" \ + "$HOME/.claude/plugins/marketplaces/hyperfleet-claude-plugins/hyperfleet-jira"; do + [ -n "$root" ] || continue + found=$(find "$root" -maxdepth 3 -name sprint_status.py -type f 2>/dev/null | head -1) + [ -n "$found" ] && { SPRINT="$found"; break; } + done + echo "$SPRINT" ``` + If `$SPRINT` is empty, stop and say so. The script is the command: do not fall back to hand-written JQL. -2. **Get all tickets in current sprint:** +2. **Run it:** ```bash - jira sprint list --current -p HYPERFLEET --plain 2>/dev/null + python3 "$SPRINT" --project HYPERFLEET --format markdown ``` + Options: `--today YYYY-MM-DD` for a reproducible run, `--sprint ` to report on a sprint other than the active one, `--stale-days` to move the staleness threshold, `--blocker-priority` to change which priority counts as top, `--link-style markdown|slack|bare` to match the destination, `--no-baseline` to skip the previous sprint lookup. -3. **Get tickets by status - To Do:** - ```bash - jira issue list -q"project = HYPERFLEET AND status = 'To Do'" --created-after "-30d" --plain 2>/dev/null - ``` + The script reads the sprint metadata and goal, every issue in the sprint, the story points, the movement signals, the open blockers, the previous sprint's baseline, and a capacity projection. It returns the report in one document. -4. **Get tickets by status - In Progress:** - ```bash - jira issue list -q"project = HYPERFLEET AND status = 'In Progress'" --plain 2>/dev/null - ``` +3. **Do not recompute by hand, and do not re-query Jira.** These four queries look right and return wrong answers: + - `status = Done`, `status = 'To Do'`, `priority = Highest`, `priority = High` match nothing in HYPERFLEET, which uses `Backlog` / `In Progress` / `Review` / `Closed` and `Major` / `Normal`. Use status categories, which the script does. + - `jira issue list` omits custom fields, so it cannot produce story points. Only `jira issue view --raw` has them. + - `jira issue list --paginate :` ignores `` and caps at 100, so a sprint above 100 issues truncates silently. The script pages by key range instead. + - `updated` is polluted by bulk edits: on Sprint 19, 18 tickets shared one timestamp. Movement is the most recent of the exact last status change, the last human comment and the assignment to the current owner. A `New -> Backlog` reclassification is not movement; `In Progress -> Review` is. -5. **Get tickets by status - Done (this sprint):** - ```bash - jira issue list -q"project = HYPERFLEET AND status = Done" --updated-after "-14d" --plain 2>/dev/null - ``` +4. **Reproduce the script's output.** Present its sections as given: Sprint Overview, Progress by status, Risk assessment, Carry-over, Capacity, Team workload. Keep the numbers verbatim, including the ones that look wrong; if a number is wrong, fix the script, not the text. -6. **Find blockers (high priority not done):** - ```bash - jira issue list -q"project = HYPERFLEET AND priority = Highest AND status != Done" --plain 2>/dev/null - jira issue list -q"project = HYPERFLEET AND priority = High AND status != Done" --plain 2>/dev/null - ``` + Three definitions matter when you read it: + - **Progress** is shown twice, by story points and by item count. The bar and the headline percentage use story points. Say which one you are quoting. + - **Movement** is the most recent of the exact last status change, the last human comment and the assignment to the current owner. The status and assignment parts need `JIRA_API_TOKEN`; without it the report falls back to `statusCategoryChangedDate` and comments only, so an item can look older than it is. + - **Capacity** is a projection from the previous sprint's pace, not a commitment. At the start of a sprint it is mostly noise; from mid-sprint on it is the number to argue with. -7. **Find unassigned tickets:** - ```bash - jira issue list -q"project = HYPERFLEET AND assignee is EMPTY AND sprint in openSprints()" --plain 2>/dev/null - ``` +5. **Add Recommendations.** The script cannot write these: they need a decision. + - Each recommendation names who decides and a due date. A follow-up with no name and no date is not a follow-up. + - `Owner` in the report body means the Jira assignee; `decided by` means the person accountable for the recommendation. They are different roles and the report must not reuse the word `owner` for both: a recommendation about unassigned tickets has a decider, not an owner. + - Order by what unblocks the most work: an unassigned item that blocks seven others outranks an unassigned item that blocks none. + - When the `Blocked by open work` list is long, recommend clearing the blockers rather than chasing the blocked items. The blocked owners cannot move. + - Never recommend "add more people" without naming the item and the person. + - For large work items (5 and 8 SP), point the lead to `/sprint-pulse-check` instead of expanding this report. + +6. **Keep the report in English.** The chat reply that accompanies it follows the user's language. + +## Ticket References + +Every key in the report must be resolvable, and no table may turn into link soup. + +- Print the base URL once, in Sprint Overview. The script emits it as `Jira: /browse/`, read from the `server:` entry in `~/.config/.jira/.config.yml`. It is the fallback for every key that stays bare. +- Link each item's own key once, at the start of its Blockers, Highest-priority, Stale or Carry-Over line. That is where the reader acts. Blocker keys inside the same line stay bare: that is what keeps a long line readable. +- The report's tables carry no ticket keys. If a table ever lists tickets, link the key there too. +- Never link the same ticket twice in the same section. + +Match the syntax to the destination, because only one of the three renders all of them: + +| Destination | Syntax | How | +|---|---|---| +| Chat / TUI | `[HYPERFLEET-XXXX](url)` | default; the script emits this | +| Slack | `` | run the script with `--link-style slack` | +| Plain log / paste | `HYPERFLEET-XXXX` | run the script with `--link-style bare` | ## Output Format +The script's `--format markdown` output **is** the report: present it as Markdown, then add Recommendations. + +**Never wrap the whole report in a code fence.** A fenced block disables Markdown, so the tables reach the reader as rows of `|` characters. The fences in the shapes below are illustrative; do not copy them into the reply. Use a fenced `text` block only when the destination cannot render tables (Slack, email, a plain log file), and say which destination you are formatting for. + +The sections below describe the report's shape so you can check that nothing is missing, not a template to retype. + ### Sprint Overview -``` +```text Sprint: [Sprint Name] -Duration: [Start Date] - [End Date] +Goal: [Sprint Goal] +Duration: [Start Date] - [End Date] (N days) Days Remaining: X days +Previous sprint baseline: X SP committed / X SP delivered (X%) across N items +Scope: X SP committed vs X SP delivered in the previous sprint (+/-X%) +Jira: https:///browse/ ``` ### Progress Summary -| Status | Count | Story Points | -|--------|-------|--------------| -| To Do | X | X pts | -| In Progress | X | X pts | -| Done | X | X pts | -| **Total** | **X** | **X pts** | +```text +| Status | Category | Count | Story Points | +|--------|----------|-------|--------------| +| [real status name] | [To Do / In Progress / Done] | X | X | +| **Total** | | **X** | **X** | -Progress: [=========> ] 65% complete +Progress: [=====> ] X% by SP (X of X) | X% by count (X of X) +``` ### Risk Assessment -#### Blockers & High Priority -- TICKET-1: [Summary] - Assigned to [Name] - [X days in status] -- TICKET-2: [Summary] - **UNASSIGNED** +#### Blocked by open work +- KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - blocked by KEY (Status), KEY (Status) + +#### Highest-priority open items +- KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - [X days without movement] + +#### Stale in progress/review +- KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - [X days without movement] -#### At-Risk Items -- Tickets in progress > 5 days without update -- Tickets without story points -- Unassigned tickets +#### Missing data +- Unestimated open items: X +- Unassigned open items: X / X SP -#### Carry-Over Risk -- Tickets likely to spill: X -- Story points at risk: X +### Carry-Over and Capacity +```text +Needs a decision: X items / X SP (X unassigned, X stale, X unestimated; a ticket can be listed twice) +Capacity: X SP remaining; at the previous sprint's pace the team delivers X SP +in the X days left (X SP over capacity, or X SP of headroom) +``` + +Headroom is a finding, not a compliment: it means the sprint committed less than +the team delivers. Report it with the same weight as an overage. ### Team Workload -| Team Member | To Do | In Progress | Done | -|-------------|-------|-------------|------| -| [Name] | X | X | X | +Open items only: closed work is already in the Progress Summary, and mixing the +two makes the Unassigned row disagree with the Missing data section. + +| Team Member | [Status] | [Status] | ... | Open SP | +|-------------|----------|----------|-----|---------| +| [Name] | X | X | ... | X | +| Unassigned | X | X | ... | X | ### Recommendations -- List actionable items for the team lead -- Highlight tickets needing attention -- Suggest re-assignments if workload is unbalanced +- [Action] - decided by: [Name] - due: [date] +- [Action] - decided by: [Name] - due: [date] diff --git a/hyperfleet-jira/scripts/pulse_check.py b/hyperfleet-jira/scripts/pulse_check.py new file mode 100755 index 0000000..0a00f05 --- /dev/null +++ b/hyperfleet-jira/scripts/pulse_check.py @@ -0,0 +1,649 @@ +#!/usr/bin/env python3 +"""Pulse check data collector for the HyperFleet sprint pulse check. + +Reads the open large work items (>= --min-sp story points) of the active sprint, +computes how long each has been without movement, resolves open blockers, and +prints the nudge queue as JSON (default) or as a ready-to-paste text block. + +Movement is the most recent of: + - the exact last status change, from the Jira changelog; a New -> Backlog + reclassification is ignored, while In Progress -> Review counts + - the last human comment (authors whose accountType is not "app") + - the assignment to the current owner, from the same changelog + +The status and assignment signals need `JIRA_API_TOKEN`; without it the script +falls back to `statusCategoryChangedDate` plus comments and says the signal is +partial. The `updated` field is deliberately ignored: bulk edits make untouched +tickets look active (on Sprint 19, 18 tickets shared one `updated` timestamp). + +Read-only. The script never writes to Jira. + +Usage: + python3 pulse_check.py # JSON, current sprint, today + python3 pulse_check.py --format text # ready-to-paste block + python3 pulse_check.py --today 2026-11-03 # reproducible run + python3 pulse_check.py --project HYPERFLEET --min-sp 5 --max-rows 7 +""" + +from __future__ import annotations + +import argparse +import base64 +import json +import os +import re +import subprocess +import sys +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from datetime import date, datetime, timezone +from pathlib import Path + + +class PulseError(Exception): + pass + + +# A move between these statuses is classification, not work. HYPERFLEET creates +# issues in `New`; a bulk New -> Backlog sweep must not reset the movement clock. +TRIVIAL_STATUSES = {"New", "Backlog"} + + +def status_change_counts(change: dict) -> bool: + """True when a status transition is workflow movement, not classification.""" + from_status = (change.get("fromString") or "").strip() + to_status = (change.get("toString") or "").strip() + return not (from_status in TRIVIAL_STATUSES and to_status in TRIVIAL_STATUSES) + + +def run_jira(args: list[str], binary: str) -> str: + proc = subprocess.run([binary, *args], capture_output=True, text=True) + if proc.returncode != 0: + raise PulseError( + f"jira {' '.join(args)} failed ({proc.returncode}): " + f"{(proc.stderr or proc.stdout).strip()[:300]}" + ) + return proc.stdout + + +def parse_date(value: str) -> date: + return datetime.strptime(value[:10], "%Y-%m-%d").date() + + +def jira_base_url() -> str | None: + """Read the server from the jira-cli config, so the report never hardcodes it. + + Bare keys are only resolvable if the reader knows the server; one line here + saves every table from carrying a link per row. + """ + config = Path.home() / ".config" / ".jira" / ".config.yml" + try: + text = config.read_text() + except OSError: + return None + match = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) + if not match: + return None + server = match.group(1).rstrip("/") + if not server.startswith("http"): + server = f"https://{server}" + return f"{server}/browse/" + + +def ticket_ref(key: str, base_url: str | None, style: str) -> str: + """Render a ticket key for the destination. + + The same report is pasted into the TUI, Slack and log files, and only one of + the three understands `[text](url)`. Keep the syntax switchable instead of + guessing at render time. + """ + if not base_url or style == "bare": + return key + url = f"{base_url}{key}" + if style == "slack": + return f"<{url}|{key}>" + return f"[{key}]({url})" + + +def prose(text: str) -> str: + return " ".join(str(text or "").split()) + + +def cell(text: str) -> str: + """One table cell: no pipes, no newlines, whatever the text contains.""" + return prose(text).replace("|", "\\|") + + +def jira_api() -> tuple[str, str] | None: + """(server, basic-auth header) for Jira's REST API, or None. + + The changelog is the only place Jira records the exact status transition and + the owner change, and jira-cli exposes neither. The token is the same + `JIRA_API_TOKEN` the CLI uses; without it both signals are unavailable and the + scripts fall back to `statusCategoryChangedDate`. + """ + token = os.environ.get("JIRA_API_TOKEN") + if not token: + return None + config = Path.home() / ".config" / ".jira" / ".config.yml" + try: + text = config.read_text() + except OSError: + return None + server = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) + login = re.search(r"^login:\s*(\S+)", text, re.MULTILINE) + if not server or not login: + return None + base = server.group(1).rstrip("/") + if not base.startswith("http"): + base = f"https://{base}" + auth = base64.b64encode(f"{login.group(1)}:{token}".encode()).decode() + return base, auth + + +def changelog_dates( + key: str, account_id: str | None, api: tuple[str, str] | None +) -> tuple[date | None, date | None]: + """(last status change, date the current assignee took the issue). + + Both come from the same changelog payload, so the report pays one request per + issue. `statusCategoryChangedDate` is a fallback, not the truth: it ignores + moves inside a category, such as In Progress -> Review. + + Either value is None when the changelog has no such entry (the issue was + created in its current status or already assigned) or the API is unreachable. + None means "unknown", not "today". + """ + if not api: + return None, None + server, auth = api + url = f"{server}/rest/api/3/issue/{key}?expand=changelog&fields=status,assignee" + request = urllib.request.Request( + url, headers={"Authorization": f"Basic {auth}", "Accept": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=15) as response: + payload = json.load(response) + except (urllib.error.URLError, OSError, json.JSONDecodeError): + return None, None + + status_dates: list[date] = [] + assignment_dates: list[date] = [] + for entry in (payload.get("changelog") or {}).get("histories") or []: + changed_status = changed_assignee = False + for change in entry.get("items") or []: + if change.get("field") == "status": + if status_change_counts(change): + changed_status = True + elif ( + account_id + and change.get("field") == "assignee" + and change.get("to") == account_id + ): + changed_assignee = True + if changed_status: + status_dates.append(parse_date(entry["created"])) + if changed_assignee: + assignment_dates.append(parse_date(entry["created"])) + + status_entered = max(status_dates) if status_dates else None + assigned = max(assignment_dates) if assignment_dates else None + return status_entered, assigned + + +def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: + """Reset the movement clock on an exact status change or a new owner. + + `statusCategoryChangedDate` only moves between To Do / In Progress / Done, so + an item that entered Review yesterday can still look stale by the category + date. The changelog has the exact transition. + + Assignment matters for the same reason blocked time does: time before the + current owner had the ticket is not the current owner's time. Both signals can + only lower the clock; neither can raise it. + """ + for item in items: + item["status_entered"] = None + item["assigned"] = None + item["days_since_assignment"] = None + + api = jira_api() + if not api: + return {"available": False, "reason": "JIRA_API_TOKEN or jira-cli login not configured"} + if not items: + return {"available": True, "checked": 0, "status_dates": 0, "assignments": 0} + + with ThreadPoolExecutor(max_workers=jobs) as pool: + dates = list( + pool.map( + lambda item: changelog_dates(item["key"], item.get("assignee_id"), api), + items, + ) + ) + + status_found = assignment_found = 0 + for item, (status_entered, assigned) in zip(items, dates): + if status_entered: + status_found += 1 + item["status_entered"] = status_entered.isoformat() + item["days_in_status"] = min( + item["days_in_status"], (today - status_entered).days + ) + if assigned: + assignment_found += 1 + item["assigned"] = assigned.isoformat() + item["days_since_assignment"] = (today - assigned).days + + signals = [item["days_in_status"]] + if item["days_since_comment"] is not None: + signals.append(item["days_since_comment"]) + if item["days_since_assignment"] is not None: + signals.append(item["days_since_assignment"]) + item["days_without_movement"] = min(signals) + + return { + "available": True, + "checked": len(items), + "status_dates": status_found, + "assignments": assignment_found, + } + + +def active_sprint(project: str, binary: str) -> dict: + out = run_jira( + [ + "sprint", "list", "-p", project, "--state", "active", + "--plain", "--no-truncate", + "--columns", "ID,NAME,START,END,STATE", + ], + binary, + ) + rows = [line.split("\t") for line in out.strip().splitlines()] + if len(rows) < 2: + raise PulseError(f"no active sprint found for project {project}") + if len(rows) > 2: + print(f"warning: {len(rows) - 1} active sprints; using {rows[1][1]}", file=sys.stderr) + sid, name, start, end, state = (rows[1] + [""] * 5)[:5] + return {"id": sid, "name": name, "start": start[:10], "end": end[:10], "state": state} + + +def large_item_keys(project: str, min_sp: int, sp_field_name: str, binary: str) -> list[str]: + jql = ( + f'project = {project} AND sprint in openSprints() ' + f'AND "{sp_field_name}" >= {min_sp} AND status != Closed' + ) + out = run_jira( + ["issue", "list", "-q", jql, "-p", project, "--plain", "--no-headers", "--columns", "KEY"], + binary, + ) + return [line.strip() for line in out.splitlines() if line.strip()] + + +def fetch_issue(key: str, project: str, binary: str) -> dict: + try: + return json.loads(run_jira(["issue", "view", key, "-p", project, "--raw"], binary)) + except (PulseError, json.JSONDecodeError) as exc: + raise PulseError(f"could not read {key}: {exc}") from exc + + +def fetch_all(keys: list[str], project: str, binary: str, jobs: int) -> dict[str, dict]: + unique = sorted(set(keys)) + with ThreadPoolExecutor(max_workers=jobs) as pool: + docs = list(pool.map(lambda k: fetch_issue(k, project, binary), unique)) + return {doc["key"]: doc for doc in docs} + + +def link_targets(doc: dict) -> tuple[list[str], list[str]]: + """Return (blocked_by, blocks) keys from the issue links. + + Orientation matters: Jira labels every Blocks link with inward="is blocked by" + and outward="blocks", so the type label alone cannot tell you the direction. + What decides is which side of the link carries the other issue. + """ + blocked_by, blocks = [], [] + for link in doc["fields"].get("issuelinks") or []: + kind = link.get("type") or {} + inward, outward = link.get("inwardIssue"), link.get("outwardIssue") + if inward and inward.get("key") and (kind.get("inward") or "").strip().lower() == "is blocked by": + blocked_by.append(inward["key"]) + elif outward and outward.get("key") and (kind.get("outward") or "").strip().lower() == "blocks": + blocks.append(outward["key"]) + return blocked_by, blocks + + +def human_comment_dates(doc: dict) -> list[date]: + dates = [] + for comment in (doc["fields"].get("comment") or {}).get("comments") or []: + author = comment.get("author") or {} + if author.get("accountType") == "app": + continue + created = comment.get("created") + if created: + dates.append(parse_date(created)) + return dates + + +def describe(key: str, doc: dict, sp_field: str, today: date) -> dict: + fields = doc["fields"] + status_changed = parse_date(fields["statuscategorychangedate"]) + comments = human_comment_dates(doc) + last_comment = max(comments) if comments else None + days_in_status = (today - status_changed).days + days_since_comment = (today - last_comment).days if last_comment else None + signals = [days_in_status] + ([days_since_comment] if days_since_comment is not None else []) + blocked_by, blocks = link_targets(doc) + return { + "key": key, + "summary": fields.get("summary", ""), + "type": (fields.get("issuetype") or {}).get("name", ""), + "sp": fields.get(sp_field) or 0, + "owner": ((fields.get("assignee") or {}).get("displayName") or "").strip(), + "assignee_id": (fields.get("assignee") or {}).get("accountId") or None, + "status": (fields.get("status") or {}).get("name", ""), + "priority": (fields.get("priority") or {}).get("name", ""), + "epic": (fields.get("parent") or {}).get("key"), + "labels": fields.get("labels") or [], + "created": (fields.get("created") or "")[:10], + "days_without_movement": min(signals), + "days_in_status": days_in_status, + "days_since_comment": days_since_comment, + "last_comment": last_comment.isoformat() if last_comment else None, + "blocked_by": blocked_by, + "blocks": blocks, + } + + +def assignment_is_binding(item: dict) -> bool: + """True when the assignment date is what keeps the clock short. + + A tie with the status change is not a reason to mention the assignment: the + status already explains it. + """ + days = item.get("days_since_assignment") + if days is None: + return False + others = [item["days_in_status"]] + if item.get("days_since_comment") is not None: + others.append(item["days_since_comment"]) + return days < min(others) + + +def is_spike(item: dict) -> bool: + """A spike reads its evidence into a document, not into a PR.""" + return item.get("summary", "").lstrip().upper().startswith(("SPIKE", "[SPIKE]")) + + +def suggested_ask(item: dict) -> str: + """One imperative per item: verb first, then who and what artifact. + + The verb comes from a fixed set - ask to approve/reject, assign, unblock, + post, start, propose a split - so the column can be scanned and counted. + The item's own age lives in the `Status . age` cell, so the text never + repeats it; a blocker"s age does appear, because that clock is not in the + table and it is what makes the blocker urgent or not. + """ + if item["open_blockers"]: + # A blocker in Review is the one an ask can move today, so it leads. + detail = sorted( + item["blocker_detail"], + key=lambda d: (d["status"] != "Review", d["key"]), + ) + clauses = [] + for d in detail: + days = d.get("days_in_status") + when = f" {days}d" if days is not None else "" + if d["status"] == "Review" and d.get("owner"): + clauses.append( + f"ask {d['owner'].split()[0]} to approve or reject {d['key']} " + f"(Review{when})" + ) + elif not d.get("owner"): + clauses.append(f"assign {d['key']}") + elif d["status"] == "In Progress": + clauses.append(f"ask {d['owner'].split()[0]} for the status of {d['key']}") + else: + clauses.append(f"ask {d['owner'].split()[0]} to start or drop {d['key']}") + shown = "; ".join(clauses[:2]) + more = f" (+{len(clauses) - 2} more)" if len(clauses) > 2 else "" + return shown[0].upper() + shown[1:] + more + if item["status"] == "Review": + return "Ask a reviewer to approve or reject" + if item["status"] == "In Progress": + if item["days_without_movement"] >= 20: + return "Propose a split with dates, or re-scope" + if item["days_without_movement"] >= 10: + return "Post the blocker or the PR link on the ticket" + return "Post the open questions on the ticket" + if item["days_without_movement"] >= 20: + if is_spike(item): + return "Post the decision note this week or drop from the sprint" + return "Start this week or drop from the sprint" + if item["days_without_movement"] >= 10: + return "Post a start date and the first step on the ticket" + return "Confirm a start date on the ticket" + + +def build(args) -> dict: + today = parse_date(args.today) if args.today else datetime.now(timezone.utc).date() + sprint = active_sprint(args.project, args.jira) + keys = large_item_keys(args.project, args.min_sp, args.sp_field_name, args.jira) + docs = fetch_all(keys, args.project, args.jira, args.jobs) + + items = [describe(k, d, args.sp_field, today) for k, d in docs.items()] + + # Resolve the status of every link target so "blocked" and "blocks" mean open work only. + targets = {k for item in items for k in item["blocked_by"] + item["blocks"]} - set(docs) + extra = fetch_all(sorted(targets), args.project, args.jira, args.jobs) if targets else {} + status_of = {k: (d["fields"].get("status") or {}).get("name", "") for k, d in docs.items()} + status_of.update({k: (d["fields"].get("status") or {}).get("name", "") for k, d in extra.items()}) + owner_of = { + k: (((d["fields"].get("assignee") or {}).get("displayName")) or "").strip() + for k, d in {**docs, **extra}.items() + } + + # Descriptors for the targets as well, so a blocker's ask can carry its own age. + target_items = [describe(k, d, args.sp_field, today) for k, d in extra.items()] + by_key = {entry["key"]: entry for entry in items + target_items} + + # Exact status transitions and owner changes reset the movement clock. Must run + # before the asks are derived. + signals = apply_changelog_signals(items + target_items, today, args.jobs) + + for item in items: + item["open_blockers"] = [k for k in item["blocked_by"] if status_of.get(k) != "Closed"] + item["blocked"] = bool(item["open_blockers"]) + item["blocker_detail"] = [ + { + "key": k, + "status": status_of.get(k, "?"), + "owner": owner_of.get(k) or None, + "days_in_status": by_key[k]["days_in_status"] if k in by_key else None, + } + for k in item["open_blockers"] + ] + item["blocks_open"] = [k for k in item["blocks"] if status_of.get(k) != "Closed"] + item["ask"] = suggested_ask(item) + + owned = [i for i in items if i["owner"]] + unowned = [i for i in items if not i["owner"]] + for item in owned: + item["needs_action"] = item["days_without_movement"] >= args.action_after + + needing = sorted( + [i for i in owned if i["needs_action"]], key=lambda i: -i["days_without_movement"] + ) + queue = needing[: args.max_rows] + + escalation = [i["key"] for i in needing if i["days_without_movement"] >= 20 and not i["blocked"]] + excluded = [i["key"] for i in needing if i["days_without_movement"] >= 20 and i["blocked"]] + + gating = sorted( + [i for i in unowned if i["blocks_open"]], key=lambda i: -len(i["blocks_open"]) + ) + + owners: dict[str, dict] = {} + for item in owned: + bucket = owners.setdefault(item["owner"], {"owner": item["owner"], "items": 0, "sp": 0}) + bucket["items"] += 1 + bucket["sp"] += item["sp"] + + return { + "generated_for": today.isoformat(), + "project": args.project, + "jira_base_url": jira_base_url(), + "link_style": args.link_style, + "sprint": sprint, + "definition": ( + "Movement = the most recent of the exact last status change, the last human " + "comment and the assignment to the current owner; a New to Backlog " + "reclassification is not movement, and the `updated` field is ignored " + "because bulk edits inflate it" + ), + "changelog_signal": signals, + "totals": { + "items": len(items), + "sp": sum(i["sp"] for i in items), + "owned": {"items": len(owned), "sp": sum(i["sp"] for i in owned)}, + "unowned": {"items": len(unowned), "sp": sum(i["sp"] for i in unowned)}, + }, + "queue": queue, + "queue_needing_action": len(needing), + "queue_overflow": max(0, len(needing) - len(queue)), + "no_action": [ + { + "key": i["key"], + "owner": i["owner"], + "days_without_movement": i["days_without_movement"], + "days_in_status": i["days_in_status"], + "days_since_comment": i.get("days_since_comment"), + "days_since_assignment": i.get("days_since_assignment"), + "assigned": i.get("assigned"), + } + for i in sorted(owned, key=lambda i: i["days_without_movement"]) + if not i["needs_action"] + ], + "escalation_20d": escalation, + "escalation_excluded_blocked": excluded, + "assignment_gap": { + "items": len(unowned), + "sp": sum(i["sp"] for i in unowned), + "sizes": sorted({i["sp"] for i in unowned}), + "blocking_other_work": [ + {"key": i["key"], "sp": i["sp"], "blocks_open": len(i["blocks_open"])} for i in gating + ], + "keys": [i["key"] for i in sorted(unowned, key=lambda i: -i["days_without_movement"])], + }, + "concentration": sorted(owners.values(), key=lambda o: (-o["sp"], -o["items"])), + "next_pulse": args.next_pulse, + } + + +def render_text(data: dict) -> str: + sprint = data["sprint"] + totals = data["totals"] + lines = [f"Pulse check - {sprint['name']}, {data['generated_for']}"] + if data.get("jira_base_url"): + lines.append(f"Jira: {data['jira_base_url']}") + lines.append("") + + queue = data["queue"] + base_url = data.get("jira_base_url") + style = data.get("link_style", "markdown") + lines.append( + f"Nudge queue ({len(queue)} of {totals['owned']['items']} owned large items need action):" + ) + if queue: + lines.append("") + lines.append("| Ticket | Title | Owner | SP | Status · age | Ask |") + lines.append("|--------|-------|-------|----|--------------|-----|") + for item in queue: + when = f"{item['days_without_movement']}d" + if assignment_is_binding(item): + when += f" (assigned {item['assigned'][5:]})" + elif item["status"] == "Backlog": + when += f" (since {item['created'][5:]})" + lines.append( + f"| {ticket_ref(item['key'], base_url, style)} | {cell(item['summary'])} | " + f"{item['owner'].split()[0]} | {int(item['sp'])} | " + f"{item['status']} · {when} | {cell(item['ask'])} |" + ) + else: + lines.append("nothing needs action this pulse") + if data["queue_overflow"]: + lines.append(f"+{data['queue_overflow']} more items need action") + + if data["no_action"]: + entries = [] + for i in data["no_action"]: + entry = f"{i['key']} ({i['days_without_movement']}d" + if assignment_is_binding(i) and i.get("assigned"): + entry += f", assigned {i['assigned'][5:]}" + entries.append(f"{entry})") + lines.append(f"\nNo action: {', '.join(entries)}") + + if data["escalation_20d"]: + lines.append(f"\nEscalation 20+ days: {', '.join(data['escalation_20d'])}" + " — lead decides: start, split, re-scope or drop") + if data["escalation_excluded_blocked"]: + lines.append(f"(excluded as blocked: {', '.join(data['escalation_excluded_blocked'])})") + + gap = data["assignment_gap"] + if gap["items"]: + sizes = ", ".join(f"{int(s)} SP" for s in gap["sizes"]) or "n/a" + lines.append(f"\nAssignment gap: {gap['items']} items / {int(gap['sp'])} SP have no owner") + lines.append(f"- sizes present: {sizes}") + if gap["blocking_other_work"]: + top = ", ".join( + f"{o['key']} (blocks {o['blocks_open']})" for o in gap["blocking_other_work"][:4] + ) + lines.append(f"- assign these first: {top}") + + if data["concentration"]: + top = data["concentration"][0] + if top["items"] > 1: + lines.append( + f"\nConcentration: {top['owner']} holds {top['items']} of " + f"{totals['owned']['items']} owned items ({int(top['sp'])} of " + f"{int(totals['owned']['sp'])} SP)" + ) + + lines.append("") + lines.append(data["definition"]) + lines.append(f"Next pulse: {data['next_pulse'] or 'to be scheduled'}") + return "\n".join(lines) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Collect the sprint pulse check data.") + parser.add_argument("--project", default="HYPERFLEET") + parser.add_argument("--jira", default="jira", help="jira-cli binary") + parser.add_argument("--min-sp", type=int, default=5) + parser.add_argument("--max-rows", type=int, default=7) + parser.add_argument("--action-after", type=int, default=5, help="days without movement that trigger an ask") + parser.add_argument("--sp-field", default="customfield_10028", help="custom field id holding story points") + parser.add_argument("--sp-field-name", default="Story Points", help="JQL name of the story points field") + parser.add_argument("--today", help="YYYY-MM-DD, for reproducible runs") + parser.add_argument("--next-pulse", help="YYYY-MM-DD printed in the text output") + parser.add_argument( + "--link-style", + choices=["markdown", "slack", "bare"], + default="markdown", + help="how ticket keys are rendered in the table", + ) + parser.add_argument("--jobs", type=int, default=8) + parser.add_argument("--format", choices=["json", "text"], default="json") + args = parser.parse_args() + + try: + data = build(args) + except PulseError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + print(render_text(data) if args.format == "text" else json.dumps(data, indent=2, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/hyperfleet-jira/scripts/sprint_status.py b/hyperfleet-jira/scripts/sprint_status.py new file mode 100755 index 0000000..42dda28 --- /dev/null +++ b/hyperfleet-jira/scripts/sprint_status.py @@ -0,0 +1,1044 @@ +#!/usr/bin/env python3 +"""Sprint status data collector for the HyperFleet sprint status report. + +Reads the active sprint, every issue in it, and the previous sprint's baseline, +then prints one JSON document (default) or a ready-to-paste text report. + +The script exists because the numbers this report needs cannot be obtained from +`jira issue list`: + + - story points live in a custom field (`customfield_10028`), which + `jira issue list` does not return; only `jira issue view --raw` has it + - `--paginate` ignores its `` offset and caps at 100, so a sprint with + more than 100 issues truncates silently; this script pages by key range + - HYPERFLEET has no `Done` / `To Do` statuses, so `status = Done` matches + nothing; status categories are used instead + - the status and assignee changelogs are not exposed by jira-cli, so the exact + status transition and assignment signal read the REST API with + `JIRA_API_TOKEN`; without it, movement falls back to the status category date + and human comments + +Read-only. The script never writes to Jira. + +Usage: + python3 sprint_status.py # JSON, current sprint, today + python3 sprint_status.py --format markdown # ready-to-paste report + python3 sprint_status.py --today 2026-11-03 # reproducible run + python3 sprint_status.py --project HYPERFLEET --stale-days 5 + +The Markdown report contains tables. Present it as Markdown: wrapping it in a +code fence turns the tables into literal pipes. Use `--format json` when a +caller needs the numbers without the layout. +""" + +from __future__ import annotations + +import argparse +import base64 +import json +import os +import re +import subprocess +import sys +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from datetime import date, datetime, timezone +from pathlib import Path + + +class SprintError(Exception): + pass + + +CATEGORY_ORDER = {"To Do": 0, "In Progress": 1, "Done": 2} + +# A move between these statuses is classification, not work. HYPERFLEET creates +# issues in `New`; a bulk New -> Backlog sweep must not reset the movement clock. +TRIVIAL_STATUSES = {"New", "Backlog"} + + +def status_change_counts(change: dict) -> bool: + """True when a status transition is workflow movement, not classification.""" + from_status = (change.get("fromString") or "").strip() + to_status = (change.get("toString") or "").strip() + return not (from_status in TRIVIAL_STATUSES and to_status in TRIVIAL_STATUSES) + + +# -------------------------------------------------------------------------- +# jira-cli plumbing +# -------------------------------------------------------------------------- + + +def run_jira(args: list[str], binary: str) -> str: + proc = subprocess.run([binary, *args], capture_output=True, text=True) + if proc.returncode != 0: + raise SprintError( + f"jira {' '.join(args)} failed ({proc.returncode}): " + f"{(proc.stderr or proc.stdout).strip()[:300]}" + ) + return proc.stdout + + +def parse_date(value: str) -> date: + return datetime.strptime(value[:10], "%Y-%m-%d").date() + + +def key_number(key: str) -> int: + _, _, number = key.rpartition("-") + return int(number) + + +def jql_project(project: str) -> str: + return f"project = {project}" + + +def search_keys(jql: str, project: str, binary: str, limit: int = 100) -> list[str]: + """List every key matching `jql`, past the 100-issue page cap. + + `jira issue list --paginate :` ignores ``: every page + returns the same first N issues. It also rejects a limit above 100. So the + only way to walk a larger result is to move the search window with JQL + itself, using the lowest key of each batch as the next boundary. + + Returns the keys in the order the CLI emitted them, plus a `truncated` flag + is not needed: an incomplete result raises instead of lying. + """ + keys: list[str] = [] + seen: set[str] = set() + boundary: str | None = None + + for _ in range(200): + query = jql if boundary is None else f"({jql}) AND key < {boundary}" + out = run_jira( + [ + "issue", "list", "-q", query, "-p", project, + "--plain", "--no-headers", "--columns", "KEY", + "--order-by", "key", "--paginate", f"0:{limit}", + ], + binary, + ) + batch = [line.strip() for line in out.splitlines() if line.strip()] + fresh = [key for key in batch if key not in seen] + if not fresh: + return keys + keys.extend(fresh) + seen.update(fresh) + if len(batch) < limit: + return keys + boundary = min(batch, key=key_number) + + raise SprintError( + f"gave up paging after 200 batches ({len(keys)} keys); narrow the JQL" + ) + + +def sprint_rows(project: str, state: str, binary: str) -> list[dict]: + out = run_jira( + [ + "sprint", "list", "-p", project, "--state", state, + "--plain", "--no-truncate", + "--columns", "ID,NAME,START,END,STATE", + ], + binary, + ) + lines = [line for line in out.strip().splitlines() if line.strip()] + rows = [] + for line in lines[1:]: + sid, name, start, end, sprint_state = (line.split("\t") + [""] * 5)[:5] + rows.append( + { + "id": sid.strip(), + "name": name.strip(), + "start": start.strip()[:10], + "end": end.strip()[:10], + "state": sprint_state.strip(), + } + ) + return rows + + +def active_sprint(project: str, binary: str) -> dict: + rows = sprint_rows(project, "active", binary) + if not rows: + raise SprintError(f"no active sprint found for project {project}") + if len(rows) > 1: + print(f"warning: {len(rows)} active sprints; using {rows[0]['name']}", file=sys.stderr) + return rows[0] + + +def previous_sprint(project: str, binary: str) -> dict | None: + rows = sprint_rows(project, "closed", binary) + if not rows: + return None + return max(rows, key=lambda row: row["end"]) + + +def fetch_issue(key: str, project: str, binary: str) -> dict: + try: + return json.loads( + run_jira(["issue", "view", key, "-p", project, "--raw"], binary) + ) + except (SprintError, json.JSONDecodeError) as exc: + raise SprintError(f"could not read {key}: {exc}") from exc + + +def fetch_all(keys: list[str], project: str, binary: str, jobs: int) -> dict[str, dict]: + unique = sorted(set(keys), key=key_number) + with ThreadPoolExecutor(max_workers=jobs) as pool: + docs = list(pool.map(lambda key: fetch_issue(key, project, binary), unique)) + return {doc["key"]: doc for doc in docs} + + +# -------------------------------------------------------------------------- +# Issue shape +# -------------------------------------------------------------------------- + + +def link_targets(doc: dict) -> tuple[list[str], list[str]]: + """Return (blocked_by, blocks) keys from the issue links. + + Jira labels every Blocks link with inward="is blocked by" and + outward="blocks", so the type label alone cannot tell you the direction. + What decides is which side of the link carries the other issue. + """ + blocked_by, blocks = [], [] + for link in doc["fields"].get("issuelinks") or []: + kind = link.get("type") or {} + inward, outward = link.get("inwardIssue"), link.get("outwardIssue") + if ( + inward + and inward.get("key") + and (kind.get("inward") or "").strip().lower() == "is blocked by" + ): + blocked_by.append(inward["key"]) + elif ( + outward + and outward.get("key") + and (kind.get("outward") or "").strip().lower() == "blocks" + ): + blocks.append(outward["key"]) + return blocked_by, blocks + + +def human_comment_dates(doc: dict) -> list[date]: + """Comment dates written by people, not integrations. + + Jira automation comments (`author.accountType == "app"`) are not movement: + a ticket whose only recent comment came from "Automation for Jira" was not + touched by anyone. + """ + dates = [] + for comment in (doc["fields"].get("comment") or {}).get("comments") or []: + author = comment.get("author") or {} + if author.get("accountType") == "app": + continue + created = comment.get("created") + if created: + dates.append(parse_date(created)) + return dates + + +def sprint_of(doc: dict, sprint_id: str) -> dict | None: + for sprint in doc["fields"].get("customfield_10020") or []: + if str(sprint.get("id")) == str(sprint_id): + return sprint + return None + + +def describe(doc: dict, sp_field: str, today: date) -> dict: + fields = doc["fields"] + status = fields.get("status") or {} + category = (status.get("statusCategory") or {}).get("name", "") + status_changed = parse_date(fields["statuscategorychangedate"]) + comments = human_comment_dates(doc) + last_comment = max(comments) if comments else None + signals = [(today - status_changed).days] + if last_comment: + signals.append((today - last_comment).days) + blocked_by, blocks = link_targets(doc) + points = fields.get(sp_field) + + return { + "key": doc["key"], + "summary": (fields.get("summary") or "").strip(), + "type": (fields.get("issuetype") or {}).get("name", ""), + "sp": points if isinstance(points, (int, float)) else None, + "owner": ((fields.get("assignee") or {}).get("displayName") or "").strip(), + "assignee_id": (fields.get("assignee") or {}).get("accountId") or None, + "status": status.get("name", ""), + "category": category, + "priority": (fields.get("priority") or {}).get("name", ""), + "epic": (fields.get("parent") or {}).get("key"), + "created": (fields.get("created") or "")[:10], + "days_in_status": (today - status_changed).days, + "days_since_comment": (today - last_comment).days if last_comment else None, + "days_without_movement": min(signals), + "last_comment": last_comment.isoformat() if last_comment else None, + "blocked_by": blocked_by, + "blocks": blocks, + "is_done": category == "Done", + } + + +def resolve_blockers( + items: list[dict], docs: dict[str, dict], project: str, binary: str, jobs: int +) -> None: + """Annotate each item with the blockers that are still open. + + A blocker only counts while it is not Done: a closed blocker no longer + explains why the item sits still. + """ + known = set(docs) + targets = {key for item in items for key in item["blocked_by"]} - known + extra = fetch_all(sorted(targets), project, binary, jobs) if targets else {} + + status_of = { + key: { + "status": (doc["fields"].get("status") or {}).get("name", ""), + "category": ( + ((doc["fields"].get("status") or {}).get("statusCategory") or {}).get("name", "") + ), + "owner": ((doc["fields"].get("assignee") or {}).get("displayName") or "").strip(), + } + for key, doc in {**docs, **extra}.items() + } + + for item in items: + item["blocker_detail"] = [ + {"key": key, **status_of.get(key, {"status": "?", "category": "?", "owner": ""})} + for key in item["blocked_by"] + ] + item["open_blockers"] = [ + detail["key"] + for detail in item["blocker_detail"] + if detail["category"] != "Done" + ] + item["blocked"] = bool(item["open_blockers"]) + + +# -------------------------------------------------------------------------- +# Aggregates +# -------------------------------------------------------------------------- + + +def summarise(items: list[dict]) -> dict: + sp_total = sum(item["sp"] or 0 for item in items) + done = [item for item in items if item["is_done"]] + + by_status: dict[str, dict] = {} + for item in items: + bucket = by_status.setdefault( + item["status"], {"status": item["status"], "category": item["category"], "items": 0, "sp": 0} + ) + bucket["items"] += 1 + bucket["sp"] += item["sp"] or 0 + + ordered_status = sorted( + by_status.values(), + key=lambda bucket: (CATEGORY_ORDER.get(bucket["category"], 9), bucket["status"]), + ) + + by_category: dict[str, dict] = {} + for item in items: + bucket = by_category.setdefault( + item["category"], {"category": item["category"], "items": 0, "sp": 0} + ) + bucket["items"] += 1 + bucket["sp"] += item["sp"] or 0 + + done_sp = sum(item["sp"] or 0 for item in done) + return { + "items": len(items), + "sp": sp_total, + "done": {"items": len(done), "sp": done_sp}, + "remaining": { + "items": len(items) - len(done), + "sp": sp_total - done_sp, + }, + "by_status": ordered_status, + "by_category": sorted( + by_category.values(), + key=lambda bucket: CATEGORY_ORDER.get(bucket["category"], 9), + ), + "percent_by_sp": round(100 * done_sp / sp_total, 1) if sp_total else 0.0, + "percent_by_items": round(100 * len(done) / len(items), 1) if items else 0.0, + } + + +def workload(items: list[dict], statuses: list[str]) -> list[dict]: + people: dict[str, dict] = {} + for item in items: + owner = item["owner"] or "Unassigned" + bucket = people.setdefault( + owner, {"owner": owner, "items": 0, "sp": 0, "by_status": {status: 0 for status in statuses}} + ) + bucket["items"] += 1 + bucket["sp"] += item["sp"] or 0 + bucket["by_status"][item["status"]] = bucket["by_status"].get(item["status"], 0) + 1 + return sorted( + people.values(), + key=lambda person: (person["owner"] == "Unassigned", person["owner"].lower()), + ) + + +def carry_over(items: list[dict], stale_days: int) -> dict: + """Items likely to spill, named rather than guessed. + + The rule is deliberately mechanical: an item is a carry-over candidate if it + is not Done and nobody owns it, it has not moved in `stale_days`, or it has + no estimate. Those are the three things the team can still fix today. + """ + candidates = [] + for item in items: + if item["is_done"]: + continue + reasons = [] + if not item["owner"]: + reasons.append("unassigned") + if item["days_without_movement"] >= stale_days and item["category"] != "To Do": + reasons.append(f"{item['days_without_movement']}d without movement") + if item["sp"] is None or item["sp"] == 0: + reasons.append("no estimate") + if reasons: + candidates.append({**item, "reasons": reasons}) + + # Unassigned first: it is the only reason on this list the lead can clear + # today. Then the longest-stalled, then the largest. + candidates.sort( + key=lambda item: ( + 0 if not item["owner"] else 1, + -item["days_without_movement"], + -(item["sp"] or 0), + ) + ) + + by_reason = {"unassigned": 0, "stale": 0, "unestimated": 0} + for item in candidates: + if not item["owner"]: + by_reason["unassigned"] += 1 + if item["days_without_movement"] >= stale_days and item["category"] != "To Do": + by_reason["stale"] += 1 + if item["sp"] is None or item["sp"] == 0: + by_reason["unestimated"] += 1 + + return { + "items": len(candidates), + "sp": sum(item["sp"] or 0 for item in candidates), + "by_reason": by_reason, + "candidates": candidates, + } + + +def sprint_calendar(start: date, end: date, today: date) -> dict: + """Calendar days, counted the way a person counts them. + + A sprint that starts on the 2nd and ends on the 22nd is 21 days, not 20: the + end day counts. Subtracting the dates without the `+ 1` makes every report + one day short, which reads as a bug even when the arithmetic is consistent. + """ + total = max(1, (end - start).days + 1) + elapsed = min(total, max(0, (today - start).days)) + return { + "days_total": total, + "days_elapsed": elapsed, + "days_remaining": max(0, total - elapsed), + "percent_elapsed": round(100 * elapsed / total, 1), + } + + +def capacity( + remaining_sp: float, sprint: dict, baseline: dict | None, today: date +) -> dict: + """Compare what is left with what the previous sprint says the team delivers. + + This is a projection, not a promise: it assumes the last sprint's pace holds + and that the sprints are comparable. It reports the headroom as well as the + overage, because "0 SP over capacity" in a sprint that committed half of what + the team delivered last time is not good news - it is an under-committed plan. + """ + try: + start = parse_date(sprint["start"]) + end = parse_date(sprint["end"]) + except (KeyError, ValueError): + return {"available": False, "reason": "sprint dates unavailable"} + + calendar = sprint_calendar(start, end, today) + days_remaining = calendar["days_remaining"] + + if not baseline or not baseline.get("delivered_sp") or not baseline.get("days"): + return { + "available": False, + "reason": "no delivered baseline from the previous sprint", + "days_remaining": days_remaining, + "sprint_days": calendar["days_total"], + "percent_elapsed": calendar["percent_elapsed"], + } + + expected = round(baseline["delivered_sp"] * days_remaining / baseline["days"], 1) + return { + "available": True, + "days_remaining": days_remaining, + "sprint_days": calendar["days_total"], + "percent_elapsed": calendar["percent_elapsed"], + "baseline_sp": baseline["delivered_sp"], + "baseline_days": baseline["days"], + "expected_sp": expected, + "remaining_sp": remaining_sp, + "over_capacity_sp": round(max(0.0, remaining_sp - expected), 1), + "headroom_sp": round(max(0.0, expected - remaining_sp), 1), + } + + +def baseline_for( + sprint: dict | None, project: str, sp_field: str, binary: str, jobs: int, today: date +) -> dict | None: + """Previous sprint totals. + + `committed` is the SP currently sitting in that sprint, not the SP committed + on day one: Jira keeps no record of scope added or removed mid-sprint, so the + number is an upper bound. The report says so instead of implying precision + it does not have. + """ + if not sprint: + return None + jql = f'{jql_project(project)} AND sprint = {sprint["id"]}' + keys = search_keys(jql, project, binary) + if not keys: + return None + docs = fetch_all(keys, project, binary, jobs) + items = [describe(doc, sp_field, today) for doc in docs.values()] + committed = sum(item["sp"] or 0 for item in items) + delivered = sum(item["sp"] or 0 for item in items if item["is_done"]) + try: + days = (parse_date(sprint["end"]) - parse_date(sprint["start"])).days + 1 + except (KeyError, ValueError): + days = None + return { + "sprint": sprint["name"], + "id": sprint["id"], + "items": len(items), + "committed_sp": committed, + "delivered_sp": delivered, + "percent": round(100 * delivered / committed, 1) if committed else 0.0, + "days": days, + } + + +def jira_base_url() -> str | None: + """Read the server from the jira-cli config, so the report never hardcodes it.""" + config = Path.home() / ".config" / ".jira" / ".config.yml" + try: + text = config.read_text() + except OSError: + return None + match = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) + if not match: + return None + server = match.group(1).rstrip("/") + if not server.startswith("http"): + server = f"https://{server}" + return f"{server}/browse/" + + +def ticket_ref(key: str, base_url: str | None, style: str) -> str: + """Render a ticket key for the destination. + + The same report is pasted into the TUI, Slack and log files, and only one of + the three understands `[text](url)`. Keep the syntax switchable instead of + guessing at render time. + """ + if not base_url or style == "bare": + return key + url = f"{base_url}{key}" + if style == "slack": + return f"<{url}|{key}>" + return f"[{key}]({url})" + + +def jira_api() -> tuple[str, str] | None: + """(server, basic-auth header) for Jira's REST API, or None. + + The changelog is the only place Jira records the exact status transition and + the owner change, and jira-cli exposes neither. The token is the same + `JIRA_API_TOKEN` the CLI uses; without it both signals are unavailable and the + report falls back to `statusCategoryChangedDate`. + """ + token = os.environ.get("JIRA_API_TOKEN") + if not token: + return None + config = Path.home() / ".config" / ".jira" / ".config.yml" + try: + text = config.read_text() + except OSError: + return None + server = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) + login = re.search(r"^login:\s*(\S+)", text, re.MULTILINE) + if not server or not login: + return None + base = server.group(1).rstrip("/") + if not base.startswith("http"): + base = f"https://{base}" + auth = base64.b64encode(f"{login.group(1)}:{token}".encode()).decode() + return base, auth + + +def changelog_dates( + key: str, account_id: str | None, api: tuple[str, str] | None +) -> tuple[date | None, date | None]: + """(last status change, date the current assignee took the issue). + + Both come from the same changelog payload, so the report pays one request per + issue. `statusCategoryChangedDate` is a fallback, not the truth: it ignores + moves inside a category, such as In Progress -> Review. + + Either value is None when the changelog has no such entry (the issue was + created in its current status or already assigned) or the API is unreachable. + None means "unknown", not "today". + """ + if not api: + return None, None + server, auth = api + url = f"{server}/rest/api/3/issue/{key}?expand=changelog&fields=status,assignee" + request = urllib.request.Request( + url, headers={"Authorization": f"Basic {auth}", "Accept": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=15) as response: + payload = json.load(response) + except (urllib.error.URLError, OSError, json.JSONDecodeError): + return None, None + + status_dates: list[date] = [] + assignment_dates: list[date] = [] + for entry in (payload.get("changelog") or {}).get("histories") or []: + changed_status = changed_assignee = False + for change in entry.get("items") or []: + if change.get("field") == "status": + if status_change_counts(change): + changed_status = True + elif ( + account_id + and change.get("field") == "assignee" + and change.get("to") == account_id + ): + changed_assignee = True + if changed_status: + status_dates.append(parse_date(entry["created"])) + if changed_assignee: + assignment_dates.append(parse_date(entry["created"])) + + status_entered = max(status_dates) if status_dates else None + assigned = max(assignment_dates) if assignment_dates else None + return status_entered, assigned + + +def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: + """Reset the movement clock on an exact status change or a new owner. + + `statusCategoryChangedDate` only moves between To Do / In Progress / Done, so + an item that entered Review yesterday can still look stale by the category + date. The changelog has the exact transition. + + Assignment matters for the same reason blocked time does: time before the + current owner had the ticket is not the current owner's time. Both signals can + only lower the clock; neither can raise it. + """ + for item in items: + item["status_entered"] = None + item["assigned"] = None + item["days_since_assignment"] = None + + api = jira_api() + if not api: + return {"available": False, "reason": "JIRA_API_TOKEN or jira-cli login not configured"} + if not items: + return {"available": True, "checked": 0, "status_dates": 0, "assignments": 0} + + with ThreadPoolExecutor(max_workers=jobs) as pool: + dates = list( + pool.map( + lambda item: changelog_dates(item["key"], item.get("assignee_id"), api), + items, + ) + ) + + status_found = assignment_found = 0 + for item, (status_entered, assigned) in zip(items, dates): + if status_entered: + status_found += 1 + item["status_entered"] = status_entered.isoformat() + item["days_in_status"] = min( + item["days_in_status"], (today - status_entered).days + ) + if assigned: + assignment_found += 1 + item["assigned"] = assigned.isoformat() + item["days_since_assignment"] = (today - assigned).days + + signals = [item["days_in_status"]] + if item["days_since_comment"] is not None: + signals.append(item["days_since_comment"]) + if item["days_since_assignment"] is not None: + signals.append(item["days_since_assignment"]) + item["days_without_movement"] = min(signals) + + return { + "available": True, + "checked": len(items), + "status_dates": status_found, + "assignments": assignment_found, + } + + +# -------------------------------------------------------------------------- +# Report +# -------------------------------------------------------------------------- + + +def build(args) -> dict: + today = parse_date(args.today) if args.today else datetime.now(timezone.utc).date() + + if args.sprint: + sprint = next( + (row for row in sprint_rows(args.project, "active,closed", args.jira) if row["id"] == args.sprint), + None, + ) + if sprint is None: + raise SprintError(f"sprint {args.sprint} not found in project {args.project}") + else: + sprint = active_sprint(args.project, args.jira) + + jql = f'{jql_project(args.project)} AND sprint = {sprint["id"]}' + keys = search_keys(jql, args.project, args.jira) + docs = fetch_all(keys, args.project, args.jira, args.jobs) + items = [describe(doc, args.sp_field, today) for doc in docs.values()] + + goal = None + for doc in docs.values(): + sprint_field = sprint_of(doc, sprint["id"]) + if sprint_field and sprint_field.get("goal"): + goal = sprint_field["goal"] + break + + resolve_blockers(items, docs, args.project, args.jira, args.jobs) + signals = apply_changelog_signals( + [item for item in items if not item["is_done"]], today, args.jobs + ) + + totals = summarise(items) + open_items = [item for item in items if not item["is_done"]] + open_statuses = [ + bucket["status"] for bucket in totals["by_status"] if bucket["category"] != "Done" + ] + people = workload(open_items, open_statuses) + + blocked = sorted( + [item for item in open_items if item["blocked"]], + key=lambda item: (-len(item["open_blockers"]), item["key"]), + ) + high_priority = sorted( + [item for item in open_items if item["priority"] == args.blocker_priority], + key=lambda item: (item["category"] != "To Do", item["key"]), + ) + priorities_seen = sorted({item["priority"] for item in items if item["priority"]}) + + stale = sorted( + [ + item + for item in open_items + if item["category"] != "To Do" and item["days_without_movement"] >= args.stale_days + ], + key=lambda item: -item["days_without_movement"], + ) + missing_sp = [item for item in open_items if item["sp"] is None or item["sp"] == 0] + unassigned = [item for item in open_items if not item["owner"]] + + baseline = baseline_for( + previous_sprint(args.project, args.jira) if not args.no_baseline else None, + args.project, + args.sp_field, + args.jira, + args.jobs, + today, + ) + + risk = carry_over(items, args.stale_days) + projection = capacity(totals["remaining"]["sp"], sprint, baseline, today) + + start = parse_date(sprint["start"]) if sprint.get("start") else None + end = parse_date(sprint["end"]) if sprint.get("end") else None + calendar = ( + sprint_calendar(start, end, today) if start and end else {} + ) + + scope = {"committed_sp": totals["sp"], "baseline_delivered_sp": None, "delta_percent": None} + if baseline and baseline.get("delivered_sp"): + scope["baseline_delivered_sp"] = baseline["delivered_sp"] + scope["delta_percent"] = round( + 100 * (totals["sp"] - baseline["delivered_sp"]) / baseline["delivered_sp"], 1 + ) + + return { + "generated_for": today.isoformat(), + "project": args.project, + "jira_base_url": jira_base_url(), + "link_style": args.link_style, + "sprint": { + **sprint, + "goal": goal, + "days_total": calendar.get("days_total"), + "days_elapsed": calendar.get("days_elapsed"), + "days_remaining": calendar.get("days_remaining"), + "percent_elapsed": calendar.get("percent_elapsed"), + "overdue": bool(end and today > end), + }, + "totals": totals, + "scope": scope, + "workload": people, + "workload_statuses": open_statuses, + "blockers": { + "blocked": blocked, + "blocked_items": len(blocked), + "blocked_sp": sum(item["sp"] or 0 for item in blocked), + "high_priority": high_priority, + "priority_checked": args.blocker_priority, + "priorities_seen": priorities_seen, + }, + "at_risk": { + "stale": stale, + "stale_items": len(stale), + "stale_days": args.stale_days, + "missing_sp": missing_sp, + "missing_sp_items": len(missing_sp), + "unassigned": unassigned, + "unassigned_items": len(unassigned), + "unassigned_sp": sum(item["sp"] or 0 for item in unassigned), + }, + "carry_over": risk, + "baseline": baseline, + "capacity": projection, + "changelog_signal": signals, + "notes": { + "progress_basis": "percent_by_sp is closed story points over total story points", + "movement_basis": ( + "days_without_movement is the most recent of the exact last status change " + "(from the changelog), the last human comment and the assignment to the " + "current owner; the `updated` field is ignored because bulk edits inflate it" + ), + "baseline_basis": ( + "committed_sp counts the story points currently in the previous sprint, " + "not the scope committed on day one; Jira does not keep that history" + ), + }, + } + + +def bar(percent: float, width: int = 14) -> str: + """Fixed-width progress bar; the whole point is that the width never moves.""" + filled = min(width, int(round(max(0.0, percent) / 100 * width))) + if filled >= width: + return "[" + "=" * width + "]" + return "[" + "=" * filled + ">" + " " * (width - filled - 1) + "]" + + +def render_text(data: dict) -> str: + sprint = data["sprint"] + totals = data["totals"] + base_url = data.get("jira_base_url") + style = data.get("link_style", "markdown") + + def ref(key: str) -> str: + return ticket_ref(key, base_url, style) + + lines: list[str] = [] + + lines.append(f"Sprint: {sprint['name']}") + lines.append(f"Goal: {sprint.get('goal') or 'not set'}") + duration = f"{sprint.get('start') or '?'} - {sprint.get('end') or '?'}" + if sprint.get("days_total") is not None: + duration += f" ({sprint['days_total']} days)" + lines.append(f"Duration: {duration}") + if sprint.get("overdue"): + lines.append("Days Remaining: 0 - sprint end date has passed") + elif sprint.get("days_remaining") is not None: + lines.append(f"Days Remaining: {sprint['days_remaining']} days") + + baseline = data.get("baseline") + if baseline: + lines.append( + f"Previous sprint baseline: {baseline['committed_sp']:g} SP committed / " + f"{baseline['delivered_sp']:g} SP delivered ({baseline['percent']:g}%) " + f"across {baseline['items']} items ({baseline['sprint']})" + ) + else: + lines.append("Previous sprint baseline: unavailable") + scope = data.get("scope") or {} + if scope.get("baseline_delivered_sp"): + lines.append( + f"Scope: {scope['committed_sp']:g} SP committed vs " + f"{scope['baseline_delivered_sp']:g} SP delivered in the previous sprint " + f"({scope['delta_percent']:+g}%)" + ) + if data.get("jira_base_url"): + lines.append(f"Jira: {data['jira_base_url']}") + + lines.append("") + lines.append("Progress by status:") + lines.append("| Status | Category | Count | Story Points |") + lines.append("|--------|----------|-------|--------------|") + for bucket in totals["by_status"]: + lines.append( + f"| {bucket['status']} | {bucket['category']} | {bucket['items']} | {bucket['sp']:g} |" + ) + lines.append( + f"| **Total** | | **{totals['items']}** | **{totals['sp']:g}** |" + ) + lines.append( + f"Progress: {bar(totals['percent_by_sp'])} {totals['percent_by_sp']:g}% by SP " + f"({totals['done']['sp']:g} of {totals['sp']:g}) | " + f"{totals['percent_by_items']:g}% by count " + f"({totals['done']['items']} of {totals['items']})" + ) + + lines.append("") + lines.append("Risk assessment:") + + blockers = data["blockers"] + if blockers["blocked"]: + lines.append( + f"Blocked by open work ({blockers['blocked_items']} items / " + f"{blockers['blocked_sp']:g} SP):" + ) + for item in blockers["blocked"][:10]: + detail = ", ".join( + f"{d['key']} ({d['status']})" for d in item["blocker_detail"] + if d["category"] != "Done" + ) + owner = item["owner"] or "UNASSIGNED" + lines.append( + f"- {ref(item['key'])}: {item['summary']} - {owner} - {item['status']} - " + f"blocked by {detail}" + ) + if blockers["blocked_items"] > 10: + lines.append(f"+{blockers['blocked_items'] - 10} more blocked items") + else: + lines.append("Blocked by open work: none") + + if blockers["high_priority"]: + lines.append( + f"Highest-priority open items ({blockers['priority_checked']}): " + f"{len(blockers['high_priority'])}" + ) + for item in blockers["high_priority"][:5]: + owner = item["owner"] or "UNASSIGNED" + lines.append( + f"- {ref(item['key'])}: {item['summary']} - {owner} - {item['status']} " + f"({item['days_without_movement']}d without movement)" + ) + else: + seen = ", ".join(blockers["priorities_seen"]) or "none recorded" + lines.append( + f"Highest-priority open items ({blockers['priority_checked']}): none " + f"- priorities present in this sprint: {seen}" + ) + + at_risk = data["at_risk"] + lines.append( + f"Stale in progress/review (>= {at_risk['stale_days']}d without movement): " + f"{at_risk['stale_items']}" + ) + for item in at_risk["stale"][:5]: + owner = item["owner"] or "UNASSIGNED" + lines.append( + f"- {ref(item['key'])}: {item['summary']} - {owner} - {item['status']} " + f"({item['days_without_movement']}d)" + ) + if at_risk["stale_items"] > 5: + lines.append(f"+{at_risk['stale_items'] - 5} more stale items") + lines.append(f"Unestimated open items: {at_risk['missing_sp_items']}") + lines.append( + f"Unassigned open items: {at_risk['unassigned_items']} / " + f"{at_risk['unassigned_sp']:g} SP" + ) + + lines.append("") + carry = data["carry_over"] + reasons = carry["by_reason"] + lines.append( + f"Needs a decision: {carry['items']} items / {carry['sp']:g} SP " + f"({reasons['unassigned']} unassigned, {reasons['stale']} stale, " + f"{reasons['unestimated']} unestimated; a ticket can be listed twice)" + ) + + projection = data["capacity"] + if projection.get("available"): + if projection["over_capacity_sp"]: + verdict = f"{projection['over_capacity_sp']:g} SP over capacity" + else: + verdict = ( + f"{projection['headroom_sp']:g} SP of headroom - the committed scope " + "is below the previous sprint's pace" + ) + lines.append( + f"Capacity: {projection['remaining_sp']:g} SP remaining; at the previous " + f"sprint's pace the team delivers {projection['expected_sp']:g} SP in the " + f"{projection['days_remaining']} days left ({verdict})" + ) + else: + lines.append(f"Capacity: not projected ({projection.get('reason')})") + + lines.append("") + lines.append("Team workload (open items):") + statuses = data.get("workload_statuses") or [] + headers = ["Team Member"] + statuses + ["Open SP"] + lines.append("| " + " | ".join(headers) + " |") + lines.append("|" + "|".join("-" * (len(header) + 2) for header in headers) + "|") + for person in data["workload"]: + cells = " | ".join(str(person["by_status"].get(status, 0)) for status in statuses) + lines.append(f"| {person['owner']} | {cells} | {person['sp']:g} |") + + lines.append("") + lines.append("Method:") + lines.append(f"- {data['notes']['movement_basis']}") + lines.append(f"- {data['notes']['progress_basis']}") + lines.append(f"- {data['notes']['baseline_basis']}") + return "\n".join(lines) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Collect the sprint status data.") + parser.add_argument("--project", default="HYPERFLEET") + parser.add_argument("--jira", default="jira", help="jira-cli binary") + parser.add_argument("--sprint", help="sprint id; defaults to the active sprint") + parser.add_argument("--sp-field", default="customfield_10028", help="custom field id holding story points") + parser.add_argument("--blocker-priority", default="Major", help="priority name that counts as top priority") + parser.add_argument("--stale-days", type=int, default=5, help="days without movement that count as stale") + parser.add_argument("--today", help="YYYY-MM-DD, for reproducible runs") + parser.add_argument("--no-baseline", action="store_true", help="skip the previous sprint lookup") + parser.add_argument("--jobs", type=int, default=8) + parser.add_argument( + "--link-style", + choices=["markdown", "slack", "bare"], + default="markdown", + help="how ticket keys are rendered in lists", + ) + parser.add_argument("--format", choices=["json", "text", "markdown"], default="json") + args = parser.parse_args() + + try: + data = build(args) + except SprintError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + print( + render_text(data) + if args.format in ("text", "markdown") + else json.dumps(data, indent=2, ensure_ascii=False) + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/hyperfleet-jira/tests/test_pulse_check.py b/hyperfleet-jira/tests/test_pulse_check.py new file mode 100644 index 0000000..e41c61b --- /dev/null +++ b/hyperfleet-jira/tests/test_pulse_check.py @@ -0,0 +1,447 @@ +"""Tests for the pulse check collector. + +Run from the plugin directory: + + python3 -m unittest discover -s tests -v + +The cases that matter are the ones where a plausible-looking implementation +produces a wrong answer: link orientation (a "blocks" link is not a blocker) +and the human-comment rule (an app comment is not movement). +""" + +import io +import json +import sys +import unittest +from datetime import date +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) + +import pulse_check as pc # noqa: E402 + +TODAY = date(2026, 11, 3) + + +def doc( + key="HYPERFLEET-100", + *, + sp=5, + owner="A Person", + status="Backlog", + changed="2026-10-04", + comments=(), + links=(), + summary="A large item", +): + return { + "key": key, + "fields": { + "summary": summary, + "issuetype": {"name": "Story"}, + "customfield_10028": sp, + "assignee": {"displayName": owner} if owner else None, + "status": {"name": status}, + "priority": {"name": "Normal"}, + "parent": {"key": "HYPERFLEET-1"}, + "labels": [], + "created": "2026-09-01T10:00:00.000+0000", + "statuscategorychangedate": f"{changed}T10:00:00.000+0000", + "comment": {"comments": list(comments)}, + "issuelinks": list(links), + }, + } + + +def comment(created, author="A Person", account_type="atlassian"): + return {"created": f"{created}T09:00:00.000+0000", "author": {"displayName": author, "accountType": account_type}} + + +def blocks_link(target): + return { + "type": {"inward": "is blocked by", "outward": "blocks"}, + "outwardIssue": {"key": target}, + } + + +def blocked_by_link(target): + return { + "type": {"inward": "is blocked by", "outward": "blocks"}, + "inwardIssue": {"key": target}, + } + + +class LinkOrientationTest(unittest.TestCase): + def test_outward_link_is_not_a_blocker(self): + blocked_by, blocks = pc.link_targets(doc(links=[blocks_link("HYPERFLEET-200")])) + self.assertEqual(blocked_by, []) + self.assertEqual(blocks, ["HYPERFLEET-200"]) + + def test_inward_link_is_a_blocker(self): + blocked_by, blocks = pc.link_targets(doc(links=[blocked_by_link("HYPERFLEET-200")])) + self.assertEqual(blocked_by, ["HYPERFLEET-200"]) + self.assertEqual(blocks, []) + + def test_both_directions_in_one_issue(self): + blocked_by, blocks = pc.link_targets( + doc(links=[blocked_by_link("HYPERFLEET-200"), blocks_link("HYPERFLEET-201")]) + ) + self.assertEqual(blocked_by, ["HYPERFLEET-200"]) + self.assertEqual(blocks, ["HYPERFLEET-201"]) + + +class MovementTest(unittest.TestCase): + def test_app_comments_are_not_movement(self): + dates = pc.human_comment_dates( + doc(comments=[comment("2026-11-02", "Automation for Jira", "app")]) + ) + self.assertEqual(dates, []) + + def test_human_comment_is_movement(self): + dates = pc.human_comment_dates(doc(comments=[comment("2026-11-02")])) + self.assertEqual(dates, [date(2026, 11, 2)]) + + def test_movement_uses_the_most_recent_signal(self): + item = pc.describe( + "HYPERFLEET-100", + doc(changed="2026-08-25", comments=[comment("2026-10-21")]), + "customfield_10028", + TODAY, + ) + self.assertEqual(item["days_in_status"], 70) + self.assertEqual(item["days_since_comment"], 13) + self.assertEqual(item["days_without_movement"], 13) + + def test_no_comments_falls_back_to_status_change(self): + item = pc.describe( + "HYPERFLEET-100", doc(changed="2026-10-14"), "customfield_10028", TODAY + ) + self.assertEqual(item["days_without_movement"], 20) + self.assertIsNone(item["last_comment"]) + + +class ChangelogSignalTest(unittest.TestCase): + api = ("https://example.atlassian.net", "auth") + + class Response: + def __init__(self, payload): + self.payload = payload + + def __enter__(self): + return io.StringIO(json.dumps(self.payload)) + + def __exit__(self, *exc): + return False + + def item(self, **overrides): + base = { + "key": "HYPERFLEET-1671", + "owner": "Phuongnhat Nguyen", + "assignee_id": "acc-1", + "status": "Backlog", + "created": "2026-09-17", + "days_in_status": 47, + "days_since_comment": 13, + "days_without_movement": 13, + } + base.update(overrides) + return base + + def apply(self, status_entered=None, assigned=None): + with mock.patch.object(pc, "jira_api", return_value=self.api), \ + mock.patch.object(pc, "changelog_dates", return_value=(status_entered, assigned)): + return pc.apply_changelog_signals([self.item], TODAY, 1) + + def test_status_change_inside_a_category_resets_the_clock(self): + item = self.item(days_in_status=15, days_without_movement=15) + with mock.patch.object(pc, "jira_api", return_value=self.api), \ + mock.patch.object( + pc, "changelog_dates", return_value=(date(2026, 10, 30), None) + ): + report = pc.apply_changelog_signals([item], TODAY, 1) + self.assertEqual(item["days_in_status"], 4) + self.assertEqual(item["days_without_movement"], 4) + self.assertEqual(item["status_entered"], "2026-10-30") + self.assertEqual( + report, {"available": True, "checked": 1, "status_dates": 1, "assignments": 0} + ) + + def test_assignment_resets_the_clock(self): + item = self.item() + with mock.patch.object(pc, "jira_api", return_value=self.api), \ + mock.patch.object( + pc, "changelog_dates", return_value=(None, date(2026, 10, 30)) + ): + report = pc.apply_changelog_signals([item], TODAY, 1) + self.assertEqual(item["days_without_movement"], 4) + self.assertEqual(item["assigned"], "2026-10-30") + self.assertEqual(item["days_since_assignment"], 4) + self.assertEqual(report["assignments"], 1) + + def test_signals_never_raise_the_clock(self): + item = self.item(days_in_status=2, days_since_comment=None, days_without_movement=2) + with mock.patch.object(pc, "jira_api", return_value=self.api), \ + mock.patch.object( + pc, "changelog_dates", return_value=(date(2026, 1, 1), date(2026, 1, 1)) + ): + pc.apply_changelog_signals([item], TODAY, 1) + self.assertEqual(item["days_without_movement"], 2) + + def test_missing_token_keeps_the_old_clock(self): + item = self.item() + with mock.patch.object(pc, "jira_api", return_value=None): + report = pc.apply_changelog_signals([item], TODAY, 1) + self.assertFalse(report["available"]) + self.assertEqual(item["days_without_movement"], 13) + self.assertIsNone(item["assigned"]) + self.assertIsNone(item["status_entered"]) + + def histories(self): + return { + "changelog": { + "histories": [ + {"created": "2026-09-01T10:00:00+0000", + "items": [{"field": "status", "to": "10013", + "fromString": "New", "toString": "Backlog"}]}, + {"created": "2026-10-30T19:12:32+0000", + "items": [{"field": "status", "to": "3", + "fromString": "Backlog", "toString": "In Progress"}]}, + {"created": "2026-10-31T10:00:00+0000", + "items": [{"field": "assignee", "to": "acc-1"}, + {"field": "status", "to": "10145", + "fromString": "In Progress", "toString": "Review"}]}, + {"created": "2026-11-02T09:00:00+0000", + "items": [{"field": "status", "to": "10013", + "fromString": "New", "toString": "Backlog"}]}, + ] + } + } + + def test_changelog_returns_the_latest_status_and_assignment(self): + with mock.patch.object( + pc.urllib.request, "urlopen", return_value=self.Response(self.histories()) + ): + self.assertEqual( + pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), + (date(2026, 10, 31), date(2026, 10, 31)), + ) + + def test_new_to_backlog_is_classification_not_movement(self): + payload = { + "changelog": { + "histories": [ + {"created": "2026-11-02T09:00:00+0000", + "items": [{"field": "status", "fromString": "New", "toString": "Backlog"}]} + ] + } + } + with mock.patch.object( + pc.urllib.request, "urlopen", return_value=self.Response(payload) + ): + self.assertEqual( + pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (None, None) + ) + + def test_created_in_status_has_no_transition_date(self): + payload = {"changelog": {"histories": []}} + with mock.patch.object( + pc.urllib.request, "urlopen", return_value=self.Response(payload) + ): + self.assertEqual( + pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (None, None) + ) + + def test_binding_only_when_assignment_is_strictly_shortest(self): + self.assertTrue( + pc.assignment_is_binding( + {"days_since_assignment": 4, "days_in_status": 47, "days_since_comment": 13} + ) + ) + self.assertFalse( + pc.assignment_is_binding( + {"days_since_assignment": 13, "days_in_status": 47, "days_since_comment": 13} + ) + ) + self.assertFalse( + pc.assignment_is_binding({"days_since_assignment": None, "days_in_status": 47}) + ) + + +class AskTest(unittest.TestCase): + def ask(self, status, days, blockers=None, summary="A large item"): + item = { + "summary": summary, + "status": status, + "days_without_movement": days, + "open_blockers": blockers or [], + "blocker_detail": [ + {"key": k, "status": "Review", "owner": "Someone"} for k in (blockers or []) + ], + } + return pc.suggested_ask(item) + + def test_blocked_item_names_the_blocker_and_the_move(self): + ask = self.ask("Backlog", 70, ["HYPERFLEET-1636"]) + self.assertIn("HYPERFLEET-1636", ask) + self.assertIn("approve or reject", ask) + + def test_the_ask_starts_with_a_verb(self): + for status in ("Backlog", "Review", "In Progress"): + for days in (6, 12, 25): + first = self.ask(status, days).split()[0].lower() + self.assertIn( + first, + {"ask", "assign", "post", "start", "propose", "confirm"}, + f"{status}/{days}d started with {first}", + ) + + def test_an_unowned_blocker_asks_for_an_owner(self): + item = { + "summary": "x", + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1523"], + "blocker_detail": [{"key": "HYPERFLEET-1523", "status": "Backlog", "owner": None}], + } + self.assertTrue(pc.suggested_ask(item).lower().startswith("assign")) + + def test_long_blocker_list_is_truncated(self): + ask = self.ask("Backlog", 70, ["HYPERFLEET-1", "HYPERFLEET-2", "HYPERFLEET-3"]) + self.assertIn("+1 more", ask) + + def test_review_blocker_leads_and_carries_its_age(self): + item = { + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1532", "HYPERFLEET-1636"], + "blocker_detail": [ + {"key": "HYPERFLEET-1532", "status": "Backlog", "days_in_status": 66}, + {"key": "HYPERFLEET-1636", "status": "Review", "days_in_status": 7, + "owner": "Martin Liptak"}, + ], + } + ask = pc.suggested_ask(item) + self.assertLess(ask.index("HYPERFLEET-1636"), ask.index("HYPERFLEET-1532")) + self.assertIn("Martin", ask) + self.assertIn("Review 7d", ask) + + def test_review_asks_a_reviewer_for_a_decision(self): + self.assertIn("approve or reject", self.ask("Review", 15).lower()) + + def test_twenty_days_backlog_is_start_or_drop(self): + ask = self.ask("Backlog", 25).lower() + self.assertIn("start", ask) + self.assertIn("drop", ask) + + def test_twenty_days_spike_is_a_decision_note(self): + ask = self.ask("Backlog", 43, summary="[SPIKE] ingress/TLS").lower() + self.assertIn("decision note", ask) + self.assertNotIn("start", ask) + + def test_twenty_days_in_progress_is_not_start_or_drop(self): + ask = self.ask("In Progress", 20).lower() + self.assertIn("re-scope", ask) + self.assertNotIn("drop", ask) + + def test_ten_days_asks_for_a_date_not_a_meeting(self): + self.assertIn("start date", self.ask("Backlog", 12).lower()) + self.assertNotIn("office hours", self.ask("Backlog", 12).lower()) + + +class RenderTest(unittest.TestCase): + def data(self): + return { + "generated_for": "2026-11-03", + "jira_base_url": "https://example.atlassian.net/browse/", + "link_style": "markdown", + "sprint": {"name": "Sprint 19"}, + "totals": {"owned": {"items": 1, "sp": 5}}, + "queue": [ + { + "key": "HYPERFLEET-1", + "summary": "A large item", + "owner": "A Person", + "sp": 5, + "status": "Backlog", + "days_without_movement": 60, + "created": "2026-09-04", + "days_in_status": 60, + "days_since_comment": None, + "assigned": None, + "days_since_assignment": None, + "ask": "Set a start date or drop", + } + ], + "queue_needing_action": 1, + "queue_overflow": 0, + "no_action": [], + "escalation_20d": [], + "escalation_excluded_blocked": [], + "assignment_gap": {"items": 0, "sp": 0, "sizes": [], "blocking_other_work": []}, + "concentration": [], + "definition": "movement = the most recent signal", + "next_pulse": None, + } + + def test_no_action_line_carries_the_assignment_date(self): + data = self.data() + data["no_action"] = [ + {"key": "HYPERFLEET-1671", "owner": "P", "days_without_movement": 4, + "days_in_status": 47, "days_since_comment": 13, + "days_since_assignment": 4, "assigned": "2026-10-30"} + ] + self.assertIn("No action: HYPERFLEET-1671 (4d, assigned 10-30)", pc.render_text(data)) + + def test_no_action_line_hides_an_assignment_that_is_not_the_binding_signal(self): + data = self.data() + data["no_action"] = [ + {"key": "HYPERFLEET-1751", "owner": "P", "days_without_movement": 1, + "days_in_status": 30, "days_since_comment": 1, + "days_since_assignment": 4, "assigned": "2026-10-30"} + ] + self.assertIn("No action: HYPERFLEET-1751 (1d)", pc.render_text(data)) + self.assertNotIn("assigned 10-30", pc.render_text(data)) + + def test_one_table_row_per_item_with_the_ask_last(self): + text = pc.render_text(self.data()) + self.assertIn("| Ticket | Title | Owner | SP | Status · age | Ask |", text) + self.assertIn( + "| [HYPERFLEET-1](https://example.atlassian.net/browse/HYPERFLEET-1) " + "| A large item | A | 5 | Backlog · 60d (since 09-04) " + "| Set a start date or drop |", + text, + ) + self.assertNotIn("> [", text) + + def test_a_pipe_in_the_summary_does_not_break_the_row(self): + data = self.data() + data["queue"][0]["summary"] = "Add | remove on the remote transport" + row = [line for line in pc.render_text(data).splitlines() if "HYPERFLEET-1)" in line][0] + self.assertEqual(row.count("|") - row.count("\\|"), 7) + + +class TicketRefTest(unittest.TestCase): + base = "https://example.atlassian.net/browse/" + + def test_markdown_is_the_default_shape(self): + self.assertEqual( + pc.ticket_ref("HYPERFLEET-1", self.base, "markdown"), + "[HYPERFLEET-1](https://example.atlassian.net/browse/HYPERFLEET-1)", + ) + + def test_slack_uses_angle_brackets(self): + self.assertEqual( + pc.ticket_ref("HYPERFLEET-1", self.base, "slack"), + "", + ) + + def test_bare_style_ignores_the_url(self): + self.assertEqual(pc.ticket_ref("HYPERFLEET-1", self.base, "bare"), "HYPERFLEET-1") + + def test_no_base_url_falls_back_to_bare(self): + self.assertEqual(pc.ticket_ref("HYPERFLEET-1", None, "markdown"), "HYPERFLEET-1") + + +if __name__ == "__main__": + unittest.main() diff --git a/hyperfleet-jira/tests/test_sprint_status.py b/hyperfleet-jira/tests/test_sprint_status.py new file mode 100644 index 0000000..019a9ac --- /dev/null +++ b/hyperfleet-jira/tests/test_sprint_status.py @@ -0,0 +1,341 @@ +"""Tests for the sprint status collector. + +Run from the plugin directory: + + python3 -m unittest discover -s tests -v + +The cases that matter are the ones where a plausible implementation returns a +comfortable number that is wrong: the 100-issue page cap (which silently drops +the tail of a sprint), the status names that match nothing in HYPERFLEET, and +the movement signal that counts automation comments as activity. +""" + +import sys +import unittest +from datetime import date +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) + +import sprint_status as ss # noqa: E402 + +TODAY = date(2026, 11, 3) + + +def doc( + key="HYPERFLEET-100", + *, + sp=5, + owner="A Person", + status="Backlog", + category="To Do", + priority="Normal", + changed="2026-10-04", + comments=(), + links=(), + summary="An item", +): + return { + "key": key, + "fields": { + "summary": summary, + "issuetype": {"name": "Story"}, + "customfield_10028": sp, + "assignee": {"displayName": owner} if owner else None, + "status": {"name": status, "statusCategory": {"name": category}}, + "priority": {"name": priority}, + "parent": {"key": "HYPERFLEET-1"}, + "created": "2026-09-01T10:00:00.000+0000", + "statuscategorychangedate": f"{changed}T10:00:00.000+0000", + "comment": {"comments": list(comments)}, + "issuelinks": list(links), + }, + } + + +def comment(created, author="A Person", account_type="atlassian"): + return { + "created": f"{created}T09:00:00.000+0000", + "author": {"displayName": author, "accountType": account_type}, + } + + +def item(key, *, sp=5, owner="A Person", status="Backlog", category="To Do", days=0): + return { + "key": key, + "summary": "An item", + "sp": sp, + "owner": owner, + "status": status, + "category": category, + "is_done": category == "Done", + "days_without_movement": days, + } + + +class PaginationTest(unittest.TestCase): + """`jira issue list --paginate` ignores the offset and caps at 100.""" + + def test_reads_past_the_first_hundred_issues(self): + calls = [] + + def fake_run_jira(args, binary): + calls.append(args) + jql = args[args.index("-q") + 1] + if "key <" in jql: + return "\n".join(f"HYPERFLEET-{n}" for n in range(100, 97, -1)) + "\n" + return "\n".join(f"HYPERFLEET-{n}" for n in range(200, 100, -1)) + "\n" + + with mock.patch.object(ss, "run_jira", side_effect=fake_run_jira): + keys = ss.search_keys("project = HYPERFLEET", "HYPERFLEET", "jira") + + self.assertEqual(len(keys), 103) + self.assertEqual(len(set(keys)), 103) + self.assertIn("HYPERFLEET-98", keys) + self.assertEqual(len(calls), 2) + self.assertIn("key < HYPERFLEET-101", calls[1][calls[1].index("-q") + 1]) + + def test_stops_when_a_batch_is_short(self): + with mock.patch.object( + ss, "run_jira", return_value="HYPERFLEET-3\nHYPERFLEET-2\n" + ) as fake: + keys = ss.search_keys("project = HYPERFLEET", "HYPERFLEET", "jira") + self.assertEqual(keys, ["HYPERFLEET-3", "HYPERFLEET-2"]) + self.assertEqual(fake.call_count, 1) + + +class DescribeTest(unittest.TestCase): + def test_status_category_is_read_not_status_name(self): + described = ss.describe(doc(status="Closed", category="Done"), "customfield_10028", TODAY) + self.assertTrue(described["is_done"]) + self.assertEqual(described["category"], "Done") + + def test_missing_story_points_are_none_not_zero(self): + described = ss.describe(doc(sp=None), "customfield_10028", TODAY) + self.assertIsNone(described["sp"]) + + def test_automation_comments_are_not_movement(self): + described = ss.describe( + doc(changed="2026-10-04", comments=[comment("2026-11-02", "Automation", "app")]), + "customfield_10028", + TODAY, + ) + self.assertEqual(described["days_without_movement"], 30) + self.assertIsNone(described["last_comment"]) + + def test_human_comment_resets_the_clock(self): + described = ss.describe( + doc(changed="2026-10-04", comments=[comment("2026-11-01")]), + "customfield_10028", + TODAY, + ) + self.assertEqual(described["days_without_movement"], 2) + + def test_block_link_is_not_a_blocker(self): + link = { + "type": {"inward": "is blocked by", "outward": "blocks"}, + "outwardIssue": {"key": "HYPERFLEET-200"}, + } + blocked_by, blocks = ss.link_targets(doc(links=[link])) + self.assertEqual(blocked_by, []) + self.assertEqual(blocks, ["HYPERFLEET-200"]) + + +class ChangelogSignalTest(unittest.TestCase): + def item(self, **overrides): + base = { + "key": "HYPERFLEET-1671", + "owner": "Phuongnhat Nguyen", + "assignee_id": "acc-1", + "days_in_status": 47, + "days_since_comment": 13, + "days_without_movement": 13, + } + base.update(overrides) + return base + + def test_status_change_inside_a_category_resets_the_clock(self): + subject = self.item(days_in_status=15, days_without_movement=15) + with mock.patch.object(ss, "jira_api", return_value=("https://x", "auth")), \ + mock.patch.object( + ss, "changelog_dates", return_value=(date(2026, 10, 30), None) + ): + ss.apply_changelog_signals([subject], TODAY, 1) + self.assertEqual(subject["days_in_status"], 4) + self.assertEqual(subject["days_without_movement"], 4) + self.assertEqual(subject["status_entered"], "2026-10-30") + + def test_assignment_resets_the_clock(self): + subject = self.item() + with mock.patch.object(ss, "jira_api", return_value=("https://x", "auth")), \ + mock.patch.object( + ss, "changelog_dates", return_value=(None, date(2026, 10, 30)) + ): + ss.apply_changelog_signals([subject], TODAY, 1) + self.assertEqual(subject["days_without_movement"], 4) + + def test_new_to_backlog_is_not_movement(self): + self.assertFalse( + ss.status_change_counts({"fromString": "New", "toString": "Backlog"}) + ) + self.assertTrue( + ss.status_change_counts({"fromString": "Backlog", "toString": "In Progress"}) + ) + self.assertTrue( + ss.status_change_counts({"fromString": "In Progress", "toString": "Review"}) + ) + + def test_missing_token_keeps_the_old_clock(self): + subject = self.item() + with mock.patch.object(ss, "jira_api", return_value=None): + report = ss.apply_changelog_signals([subject], TODAY, 1) + self.assertFalse(report["available"]) + self.assertEqual(subject["days_without_movement"], 13) + + +class SummariseTest(unittest.TestCase): + def test_progress_is_reported_by_points_and_by_count(self): + items = [ + item("A", sp=5, category="Done", status="Closed"), + item("B", sp=5, category="To Do"), + item("C", sp=10, category="To Do"), + ] + summary = ss.summarise(items) + self.assertEqual(summary["sp"], 20) + self.assertEqual(summary["percent_by_sp"], 25.0) + self.assertEqual(summary["percent_by_items"], 33.3) + + def test_unestimated_items_count_as_zero_points_but_as_an_item(self): + summary = ss.summarise([item("A", sp=None), item("B", sp=5, category="Done")]) + self.assertEqual(summary["sp"], 5) + self.assertEqual(summary["items"], 2) + self.assertEqual(summary["percent_by_sp"], 100.0) + + def test_statuses_are_ordered_by_category(self): + summary = ss.summarise( + [ + item("A", status="Closed", category="Done"), + item("B", status="Backlog", category="To Do"), + item("C", status="Review", category="In Progress"), + ] + ) + self.assertEqual( + [bucket["status"] for bucket in summary["by_status"]], + ["Backlog", "Review", "Closed"], + ) + + +class WorkloadTest(unittest.TestCase): + def test_unassigned_is_a_row_not_a_crash(self): + rows = ss.workload( + [item("A", owner=""), item("B", owner="B Person")], ["Backlog", "Closed"] + ) + self.assertEqual(rows[0]["owner"], "B Person") + self.assertEqual(rows[-1]["owner"], "Unassigned") + self.assertEqual(rows[-1]["items"], 1) + + +class CarryOverTest(unittest.TestCase): + def test_done_items_are_never_candidates(self): + carry = ss.carry_over( + [item("A", owner="", category="Done", status="Closed")], stale_days=5 + ) + self.assertEqual(carry["items"], 0) + + def test_unassigned_sorts_before_stale(self): + carry = ss.carry_over( + [ + item("A", status="In Progress", category="In Progress", days=40), + item("B", owner="", days=0), + ], + stale_days=5, + ) + self.assertEqual([c["key"] for c in carry["candidates"]], ["B", "A"]) + + def test_reasons_are_counted(self): + carry = ss.carry_over( + [ + item("A", owner="", sp=None), + item("B", days=10, status="Review", category="In Progress"), + ], + stale_days=5, + ) + self.assertEqual(carry["by_reason"], {"unassigned": 1, "stale": 1, "unestimated": 1}) + + def test_backlog_is_not_stale(self): + carry = ss.carry_over([item("A", days=90)], stale_days=5) + self.assertEqual(carry["by_reason"]["stale"], 0) + + +class CapacityTest(unittest.TestCase): + sprint = {"start": "2026-11-02", "end": "2026-11-22"} + + def test_days_are_counted_the_way_a_person_counts_them(self): + calendar = ss.sprint_calendar(date(2026, 11, 2), date(2026, 11, 22), TODAY) + self.assertEqual(calendar["days_total"], 21) + self.assertEqual(calendar["days_elapsed"], 1) + self.assertEqual(calendar["days_remaining"], 20) + + def test_projects_from_the_previous_pace(self): + projection = ss.capacity( + remaining_sp=120, + sprint=self.sprint, + baseline={"delivered_sp": 100, "days": 10}, + today=TODAY, + ) + self.assertTrue(projection["available"]) + self.assertEqual(projection["days_remaining"], 20) + self.assertEqual(projection["expected_sp"], 200.0) + self.assertEqual(projection["over_capacity_sp"], 0.0) + self.assertEqual(projection["headroom_sp"], 80.0) + + def test_over_capacity_is_reported_when_scope_exceeds_pace(self): + projection = ss.capacity( + remaining_sp=300, + sprint=self.sprint, + baseline={"delivered_sp": 100, "days": 10}, + today=TODAY, + ) + self.assertEqual(projection["over_capacity_sp"], 100.0) + self.assertEqual(projection["headroom_sp"], 0.0) + + def test_without_a_baseline_it_says_so_instead_of_guessing(self): + projection = ss.capacity(120, self.sprint, None, TODAY) + self.assertFalse(projection["available"]) + self.assertIn("baseline", projection["reason"]) + + +class BarTest(unittest.TestCase): + def test_width_never_moves(self): + widths = {len(ss.bar(percent)) for percent in (0, 3, 50, 99, 100)} + self.assertEqual(len(widths), 1) + + def test_full_bar_is_all_equals(self): + self.assertNotIn(">", ss.bar(100)) + + +class TicketRefTest(unittest.TestCase): + base = "https://example.atlassian.net/browse/" + + def test_markdown_is_the_default_shape(self): + self.assertEqual( + ss.ticket_ref("HYPERFLEET-1", self.base, "markdown"), + "[HYPERFLEET-1](https://example.atlassian.net/browse/HYPERFLEET-1)", + ) + + def test_slack_uses_angle_brackets(self): + self.assertEqual( + ss.ticket_ref("HYPERFLEET-1", self.base, "slack"), + "", + ) + + def test_bare_style_ignores_the_url(self): + self.assertEqual(ss.ticket_ref("HYPERFLEET-1", self.base, "bare"), "HYPERFLEET-1") + + def test_no_base_url_falls_back_to_bare(self): + self.assertEqual(ss.ticket_ref("HYPERFLEET-1", None, "markdown"), "HYPERFLEET-1") + + +if __name__ == "__main__": + unittest.main() From 8a38e6b94227e25d49551999c37894e20d0db815 Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 11:27:50 -0300 Subject: [PATCH 2/9] fix(hyperfleet-jira): address review on sprint commands - wire the $1 project argument through both commands and validate it at the CLI boundary, since the value lands in JQL unquoted - time out jira calls and turn a missing binary into a command error - require https before sending the Basic auth token - count failed changelog reads, report them in changelog_signal and render a partial-signal line instead of claiming the exact clock - pick the baseline sprint from sprints that ended before the target sprint started --- .../commands/sprint-pulse-check.md | 18 +-- hyperfleet-jira/commands/sprint-status.md | 5 +- hyperfleet-jira/scripts/pulse_check.py | 111 ++++++++++++-- hyperfleet-jira/scripts/sprint_status.py | 118 ++++++++++++--- hyperfleet-jira/tests/test_pulse_check.py | 139 +++++++++++++++++- hyperfleet-jira/tests/test_sprint_status.py | 133 +++++++++++++++++ 6 files changed, 479 insertions(+), 45 deletions(-) diff --git a/hyperfleet-jira/commands/sprint-pulse-check.md b/hyperfleet-jira/commands/sprint-pulse-check.md index 36cd786..6fc7755 100644 --- a/hyperfleet-jira/commands/sprint-pulse-check.md +++ b/hyperfleet-jira/commands/sprint-pulse-check.md @@ -29,9 +29,10 @@ This command produces a short nudge queue. It is not a sprint status report: it ``` If `$PULSE` is empty, stop and say so. The script is the command: do not reimplement the calculation inline. -2. **Run it:** +2. **Run it.** Set `PROJECT` to `$1` when the user gave a project key, and leave it unset otherwise; the script rejects anything that is not a Jira project key. ```bash - python3 "$PULSE" --project HYPERFLEET --format json + PROJECT="$1" + python3 "$PULSE" --project "${PROJECT:-HYPERFLEET}" --format json ``` Options: `--today YYYY-MM-DD` for a reproducible run, `--format text` for a ready-to-paste block, `--min-sp` and `--max-rows` to move the thresholds, `--link-style markdown|slack|bare` to match the destination, `--next-pulse YYYY-MM-DD` to print the next scheduled pulse (omit it when the lead has not scheduled one, and the output says "to be scheduled"). @@ -80,19 +81,18 @@ Nudge queue (5 of 7 owned large items need action): | Ticket | Title | Owner | SP | Status · age | Ask | |--------|-------|-------|----|--------------|-----| -| [HYPERFLEET-1413](https:///browse/HYPERFLEET-1413) | Verify N-1 to N operator upgrades converge the API operand | Tirth | 5 | In Progress · 20d | 20+ days in progress: dated plan on the ticket, or re-scope | -| [HYPERFLEET-1616](https:///browse/HYPERFLEET-1616) | SPIKE: Extend Prow testing to support OLM installs classic and v1 | Mallory | 5 | Backlog · 60d (since 09-04) | No start after 60d: set a start date this week or drop from Sprint 19 | +| [HYPERFLEET-1413](https:///browse/HYPERFLEET-1413) | Verify N-1 to N operator upgrades converge the API operand | Tirth | 5 | In Progress · 20d | Propose a split with dates, or re-scope | +| [HYPERFLEET-1616](https:///browse/HYPERFLEET-1616) | SPIKE: Extend Prow testing to support OLM installs classic and v1 | Mallory | 5 | Backlog · 60d (since 09-04) | Post the decision note this week or drop from the sprint | -No action: HYPERFLEET-1671 (4d, assigned 10-30), HYPERFLEET-1751 (commented yesterday) +No action: HYPERFLEET-1671 (4d, assigned 10-30), HYPERFLEET-1751 (1d) Assignment gap: 17 items / 85 SP have no owner -- largest: HYPERFLEET-XXXX (8 SP), HYPERFLEET-XXXX (5 SP) -- 5 SP: N items +- sizes present: 5 SP +- assign these first: HYPERFLEET-XXXX (blocks 7), HYPERFLEET-XXXX (blocks 4) Concentration: Phuongnhat holds 3 of 7 owned items (21 of 41 SP) -Movement = the most recent of the exact last status change, the last human comment and the assignment to the current owner; a New-to-Backlog reclassification is not movement. -`updated` is not used: bulk edits make untouched tickets look active. +Movement = the most recent of the exact last status change, the last human comment and the assignment to the current owner; a New to Backlog reclassification is not movement, and the `updated` field is ignored because bulk edits inflate it Next pulse: 2026-11-05 ``` diff --git a/hyperfleet-jira/commands/sprint-status.md b/hyperfleet-jira/commands/sprint-status.md index 9fe1c57..0d92493 100644 --- a/hyperfleet-jira/commands/sprint-status.md +++ b/hyperfleet-jira/commands/sprint-status.md @@ -27,9 +27,10 @@ Comprehensive sprint health report for team leads and scrum masters. ``` If `$SPRINT` is empty, stop and say so. The script is the command: do not fall back to hand-written JQL. -2. **Run it:** +2. **Run it.** Set `PROJECT` to `$1` when the user gave a project key, and leave it unset otherwise; the script rejects anything that is not a Jira project key. ```bash - python3 "$SPRINT" --project HYPERFLEET --format markdown + PROJECT="$1" + python3 "$SPRINT" --project "${PROJECT:-HYPERFLEET}" --format markdown ``` Options: `--today YYYY-MM-DD` for a reproducible run, `--sprint ` to report on a sprint other than the active one, `--stale-days` to move the staleness threshold, `--blocker-priority` to change which priority counts as top, `--link-style markdown|slack|bare` to match the destination, `--no-baseline` to skip the previous sprint lookup. diff --git a/hyperfleet-jira/scripts/pulse_check.py b/hyperfleet-jira/scripts/pulse_check.py index 0a00f05..3a55ed3 100755 --- a/hyperfleet-jira/scripts/pulse_check.py +++ b/hyperfleet-jira/scripts/pulse_check.py @@ -45,6 +45,10 @@ class PulseError(Exception): pass +class ChangelogUnavailable(Exception): + """A changelog read failed; it must not be read as "no entry".""" + + # A move between these statuses is classification, not work. HYPERFLEET creates # issues in `New`; a bulk New -> Backlog sweep must not reset the movement clock. TRIVIAL_STATUSES = {"New", "Backlog"} @@ -58,7 +62,12 @@ def status_change_counts(change: dict) -> bool: def run_jira(args: list[str], binary: str) -> str: - proc = subprocess.run([binary, *args], capture_output=True, text=True) + try: + proc = subprocess.run( + [binary, *args], capture_output=True, text=True, timeout=120 + ) + except (subprocess.TimeoutExpired, FileNotFoundError) as exc: + raise PulseError(f"jira {' '.join(args[:2])} could not run: {exc}") from exc if proc.returncode != 0: raise PulseError( f"jira {' '.join(args)} failed ({proc.returncode}): " @@ -86,8 +95,10 @@ def jira_base_url() -> str | None: if not match: return None server = match.group(1).rstrip("/") - if not server.startswith("http"): + if "://" not in server: server = f"https://{server}" + if not server.startswith("https://"): + return None return f"{server}/browse/" @@ -136,8 +147,11 @@ def jira_api() -> tuple[str, str] | None: if not server or not login: return None base = server.group(1).rstrip("/") - if not base.startswith("http"): + if "://" not in base: base = f"https://{base}" + if not base.startswith("https://"): + # The Basic auth header carries the API token; never send it in cleartext. + return None auth = base64.b64encode(f"{login.group(1)}:{token}".encode()).decode() return base, auth @@ -152,8 +166,10 @@ def changelog_dates( moves inside a category, such as In Progress -> Review. Either value is None when the changelog has no such entry (the issue was - created in its current status or already assigned) or the API is unreachable. - None means "unknown", not "today". + created in its current status or already assigned). A failed request raises + `ChangelogUnavailable` instead: "the API said no" and "the API did not + answer" must not collapse into the same value, because the caller falls back + to a different clock for the second one. """ if not api: return None, None @@ -165,8 +181,8 @@ def changelog_dates( try: with urllib.request.urlopen(request, timeout=15) as response: payload = json.load(response) - except (urllib.error.URLError, OSError, json.JSONDecodeError): - return None, None + except (urllib.error.URLError, OSError, json.JSONDecodeError) as exc: + raise ChangelogUnavailable(f"{key}: {type(exc).__name__}") from exc status_dates: list[date] = [] assignment_dates: list[date] = [] @@ -192,6 +208,21 @@ def changelog_dates( return status_entered, assigned +def read_changelog( + key: str, account_id: str | None, api: tuple[str, str] | None +) -> tuple[tuple[date | None, date | None], str | None]: + """(dates, error). A failed read is counted, not read as "no entry". + + Collapsing both into (None, None) lets an expired token walk every item back + to the status category clock while the report still calls it the exact + signal, and the 20-day rung then fires on items that moved last week. + """ + try: + return changelog_dates(key, account_id, api), None + except ChangelogUnavailable as exc: + return (None, None), str(exc) + + def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: """Reset the movement clock on an exact status change or a new owner. @@ -210,20 +241,33 @@ def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: api = jira_api() if not api: - return {"available": False, "reason": "JIRA_API_TOKEN or jira-cli login not configured"} + return { + "available": False, + "failed": 0, + "checked": len(items), + "reason": "JIRA_API_TOKEN or jira-cli login not configured", + } if not items: - return {"available": True, "checked": 0, "status_dates": 0, "assignments": 0} + return { + "available": True, + "failed": 0, + "checked": 0, + "status_dates": 0, + "assignments": 0, + } with ThreadPoolExecutor(max_workers=jobs) as pool: - dates = list( + results = list( pool.map( - lambda item: changelog_dates(item["key"], item.get("assignee_id"), api), + lambda item: read_changelog(item["key"], item.get("assignee_id"), api), items, ) ) - status_found = assignment_found = 0 - for item, (status_entered, assigned) in zip(items, dates): + status_found = assignment_found = failed = 0 + for item, ((status_entered, assigned), error) in zip(items, results): + if error: + failed += 1 if status_entered: status_found += 1 item["status_entered"] = status_entered.isoformat() @@ -243,7 +287,8 @@ def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: item["days_without_movement"] = min(signals) return { - "available": True, + "available": failed == 0, + "failed": failed, "checked": len(items), "status_dates": status_found, "assignments": assignment_found, @@ -449,6 +494,12 @@ def build(args) -> dict: # Exact status transitions and owner changes reset the movement clock. Must run # before the asks are derived. signals = apply_changelog_signals(items + target_items, today, args.jobs) + if signals.get("failed"): + print( + f"warning: {signals['failed']} of {signals['checked']} changelog reads " + "failed; those items fall back to the status category date", + file=sys.stderr, + ) for item in items: item["open_blockers"] = [k for k in item["blocked_by"] if status_of.get(k) != "Closed"] @@ -609,20 +660,48 @@ def render_text(data: dict) -> str: ) lines.append("") + signal = data.get("changelog_signal") or {} + if signal.get("failed"): + lines.append( + f"Signal: partial - {signal['failed']} of {signal['checked']} changelog " + "reads failed, so those items use the status category date" + ) + elif signal.get("available") is False: + lines.append( + "Signal: partial - no JIRA_API_TOKEN, so movement ignores exact status " + "changes and assignments" + ) lines.append(data["definition"]) lines.append(f"Next pulse: {data['next_pulse'] or 'to be scheduled'}") return "\n".join(lines) +PROJECT_KEY = re.compile(r"^[A-Z][A-Z0-9_]{1,9}$") + + +def project_key(value: str) -> str: + """A project key lands in JQL unquoted, so reject anything that is not one.""" + if not PROJECT_KEY.match(value): + raise argparse.ArgumentTypeError(f"not a Jira project key: {value!r}") + return value + + +def field_name(value: str) -> str: + """A field name sits inside quotes in JQL; keep quotes and escapes out.""" + if '"' in value or "\\" in value: + raise argparse.ArgumentTypeError(f"not a Jira field name: {value!r}") + return value + + def main() -> int: parser = argparse.ArgumentParser(description="Collect the sprint pulse check data.") - parser.add_argument("--project", default="HYPERFLEET") + parser.add_argument("--project", default="HYPERFLEET", type=project_key) parser.add_argument("--jira", default="jira", help="jira-cli binary") parser.add_argument("--min-sp", type=int, default=5) parser.add_argument("--max-rows", type=int, default=7) parser.add_argument("--action-after", type=int, default=5, help="days without movement that trigger an ask") parser.add_argument("--sp-field", default="customfield_10028", help="custom field id holding story points") - parser.add_argument("--sp-field-name", default="Story Points", help="JQL name of the story points field") + parser.add_argument("--sp-field-name", default="Story Points", type=field_name, help="JQL name of the story points field") parser.add_argument("--today", help="YYYY-MM-DD, for reproducible runs") parser.add_argument("--next-pulse", help="YYYY-MM-DD printed in the text output") parser.add_argument( diff --git a/hyperfleet-jira/scripts/sprint_status.py b/hyperfleet-jira/scripts/sprint_status.py index 42dda28..b468789 100755 --- a/hyperfleet-jira/scripts/sprint_status.py +++ b/hyperfleet-jira/scripts/sprint_status.py @@ -51,6 +51,10 @@ class SprintError(Exception): pass +class ChangelogUnavailable(Exception): + """A changelog read failed; it must not be read as "no entry".""" + + CATEGORY_ORDER = {"To Do": 0, "In Progress": 1, "Done": 2} # A move between these statuses is classification, not work. HYPERFLEET creates @@ -71,7 +75,12 @@ def status_change_counts(change: dict) -> bool: def run_jira(args: list[str], binary: str) -> str: - proc = subprocess.run([binary, *args], capture_output=True, text=True) + try: + proc = subprocess.run( + [binary, *args], capture_output=True, text=True, timeout=120 + ) + except (subprocess.TimeoutExpired, FileNotFoundError) as exc: + raise SprintError(f"jira {' '.join(args[:2])} could not run: {exc}") from exc if proc.returncode != 0: raise SprintError( f"jira {' '.join(args)} failed ({proc.returncode}): " @@ -167,8 +176,18 @@ def active_sprint(project: str, binary: str) -> dict: return rows[0] -def previous_sprint(project: str, binary: str) -> dict | None: +def previous_sprint( + project: str, binary: str, before: str | None = None +) -> dict | None: + """The sprint the target sprint is compared against. + + `--sprint` can name a closed sprint, and then the latest closed sprint may be + the target itself or a later one; only sprints that ended before the target + started are baselines. + """ rows = sprint_rows(project, "closed", binary) + if before: + rows = [row for row in rows if row["end"] and row["end"] < before] if not rows: return None return max(rows, key=lambda row: row["end"]) @@ -536,8 +555,10 @@ def jira_base_url() -> str | None: if not match: return None server = match.group(1).rstrip("/") - if not server.startswith("http"): + if "://" not in server: server = f"https://{server}" + if not server.startswith("https://"): + return None return f"{server}/browse/" @@ -577,8 +598,11 @@ def jira_api() -> tuple[str, str] | None: if not server or not login: return None base = server.group(1).rstrip("/") - if not base.startswith("http"): + if "://" not in base: base = f"https://{base}" + if not base.startswith("https://"): + # The Basic auth header carries the API token; never send it in cleartext. + return None auth = base64.b64encode(f"{login.group(1)}:{token}".encode()).decode() return base, auth @@ -593,8 +617,10 @@ def changelog_dates( moves inside a category, such as In Progress -> Review. Either value is None when the changelog has no such entry (the issue was - created in its current status or already assigned) or the API is unreachable. - None means "unknown", not "today". + created in its current status or already assigned). A failed request raises + `ChangelogUnavailable` instead: "the API said no" and "the API did not + answer" must not collapse into the same value, because the caller falls back + to a different clock for the second one. """ if not api: return None, None @@ -606,8 +632,8 @@ def changelog_dates( try: with urllib.request.urlopen(request, timeout=15) as response: payload = json.load(response) - except (urllib.error.URLError, OSError, json.JSONDecodeError): - return None, None + except (urllib.error.URLError, OSError, json.JSONDecodeError) as exc: + raise ChangelogUnavailable(f"{key}: {type(exc).__name__}") from exc status_dates: list[date] = [] assignment_dates: list[date] = [] @@ -633,6 +659,21 @@ def changelog_dates( return status_entered, assigned +def read_changelog( + key: str, account_id: str | None, api: tuple[str, str] | None +) -> tuple[tuple[date | None, date | None], str | None]: + """(dates, error). A failed read is counted, not read as "no entry". + + Collapsing both into (None, None) lets an expired token walk every item back + to the status category clock while the report still calls it the exact + signal, inflating the stale list and the "needs a decision" count. + """ + try: + return changelog_dates(key, account_id, api), None + except ChangelogUnavailable as exc: + return (None, None), str(exc) + + def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: """Reset the movement clock on an exact status change or a new owner. @@ -651,20 +692,33 @@ def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: api = jira_api() if not api: - return {"available": False, "reason": "JIRA_API_TOKEN or jira-cli login not configured"} + return { + "available": False, + "failed": 0, + "checked": len(items), + "reason": "JIRA_API_TOKEN or jira-cli login not configured", + } if not items: - return {"available": True, "checked": 0, "status_dates": 0, "assignments": 0} + return { + "available": True, + "failed": 0, + "checked": 0, + "status_dates": 0, + "assignments": 0, + } with ThreadPoolExecutor(max_workers=jobs) as pool: - dates = list( + results = list( pool.map( - lambda item: changelog_dates(item["key"], item.get("assignee_id"), api), + lambda item: read_changelog(item["key"], item.get("assignee_id"), api), items, ) ) - status_found = assignment_found = 0 - for item, (status_entered, assigned) in zip(items, dates): + status_found = assignment_found = failed = 0 + for item, ((status_entered, assigned), error) in zip(items, results): + if error: + failed += 1 if status_entered: status_found += 1 item["status_entered"] = status_entered.isoformat() @@ -684,7 +738,8 @@ def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: item["days_without_movement"] = min(signals) return { - "available": True, + "available": failed == 0, + "failed": failed, "checked": len(items), "status_dates": status_found, "assignments": assignment_found, @@ -725,6 +780,12 @@ def build(args) -> dict: signals = apply_changelog_signals( [item for item in items if not item["is_done"]], today, args.jobs ) + if signals.get("failed"): + print( + f"warning: {signals['failed']} of {signals['checked']} changelog reads " + "failed; those items fall back to the status category date", + file=sys.stderr, + ) totals = summarise(items) open_items = [item for item in items if not item["is_done"]] @@ -755,7 +816,9 @@ def build(args) -> dict: unassigned = [item for item in open_items if not item["owner"]] baseline = baseline_for( - previous_sprint(args.project, args.jira) if not args.no_baseline else None, + previous_sprint(args.project, args.jira, sprint.get("start") or None) + if not args.no_baseline + else None, args.project, args.sp_field, args.jira, @@ -1003,12 +1066,33 @@ def ref(key: str) -> str: lines.append(f"- {data['notes']['movement_basis']}") lines.append(f"- {data['notes']['progress_basis']}") lines.append(f"- {data['notes']['baseline_basis']}") + signal = data.get("changelog_signal") or {} + if signal.get("failed"): + lines.append( + f"- signal: partial - {signal['failed']} of {signal['checked']} changelog " + "reads failed, so those items use the status category date" + ) + elif signal.get("available") is False: + lines.append( + "- signal: partial - no JIRA_API_TOKEN, so movement ignores exact status " + "changes and assignments" + ) return "\n".join(lines) +PROJECT_KEY = re.compile(r"^[A-Z][A-Z0-9_]{1,9}$") + + +def project_key(value: str) -> str: + """A project key lands in JQL unquoted, so reject anything that is not one.""" + if not PROJECT_KEY.match(value): + raise argparse.ArgumentTypeError(f"not a Jira project key: {value!r}") + return value + + def main() -> int: parser = argparse.ArgumentParser(description="Collect the sprint status data.") - parser.add_argument("--project", default="HYPERFLEET") + parser.add_argument("--project", default="HYPERFLEET", type=project_key) parser.add_argument("--jira", default="jira", help="jira-cli binary") parser.add_argument("--sprint", help="sprint id; defaults to the active sprint") parser.add_argument("--sp-field", default="customfield_10028", help="custom field id holding story points") diff --git a/hyperfleet-jira/tests/test_pulse_check.py b/hyperfleet-jira/tests/test_pulse_check.py index e41c61b..d5c8d19 100644 --- a/hyperfleet-jira/tests/test_pulse_check.py +++ b/hyperfleet-jira/tests/test_pulse_check.py @@ -12,6 +12,7 @@ import io import json import sys +import tempfile import unittest from datetime import date from pathlib import Path @@ -164,7 +165,14 @@ def test_status_change_inside_a_category_resets_the_clock(self): self.assertEqual(item["days_without_movement"], 4) self.assertEqual(item["status_entered"], "2026-10-30") self.assertEqual( - report, {"available": True, "checked": 1, "status_dates": 1, "assignments": 0} + report, + { + "available": True, + "failed": 0, + "checked": 1, + "status_dates": 1, + "assignments": 0, + }, ) def test_assignment_resets_the_clock(self): @@ -268,6 +276,104 @@ def test_binding_only_when_assignment_is_strictly_shortest(self): ) +class ChangelogFailureTest(unittest.TestCase): + api = ("https://example.atlassian.net", "auth") + + def item(self): + return { + "key": "HYPERFLEET-1671", + "owner": "Phuongnhat Nguyen", + "assignee_id": "acc-1", + "days_in_status": 47, + "days_since_comment": 13, + "days_without_movement": 13, + } + + def test_a_failed_read_is_counted_not_hidden(self): + with mock.patch.object(pc, "jira_api", return_value=self.api), \ + mock.patch.object( + pc, "changelog_dates", + side_effect=pc.ChangelogUnavailable("HYPERFLEET-1671: HTTPError"), + ): + report = pc.apply_changelog_signals([self.item()], TODAY, 1) + self.assertFalse(report["available"]) + self.assertEqual(report["failed"], 1) + self.assertEqual(report["checked"], 1) + + def test_a_failed_read_leaves_the_clock_alone(self): + item = self.item() + with mock.patch.object(pc, "jira_api", return_value=self.api), \ + mock.patch.object( + pc, "changelog_dates", side_effect=pc.ChangelogUnavailable("boom") + ): + pc.apply_changelog_signals([item], TODAY, 1) + self.assertEqual(item["days_without_movement"], 13) + self.assertIsNone(item["status_entered"]) + + def test_an_http_error_raises_instead_of_looking_empty(self): + with mock.patch.object( + pc.urllib.request, + "urlopen", + side_effect=pc.urllib.error.URLError("401 Unauthorized"), + ): + with self.assertRaises(pc.ChangelogUnavailable): + pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) + + +class RunJiraTest(unittest.TestCase): + def test_a_timeout_is_a_pulse_error(self): + with mock.patch.object( + pc.subprocess, + "run", + side_effect=pc.subprocess.TimeoutExpired("jira", 120), + ): + with self.assertRaises(pc.PulseError): + pc.run_jira(["issue", "list"], "jira") + + def test_a_missing_binary_is_a_pulse_error(self): + with mock.patch.object( + pc.subprocess, "run", side_effect=FileNotFoundError("jira") + ): + with self.assertRaises(pc.PulseError): + pc.run_jira(["issue", "list"], "jira") + + +class JiraApiTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + (Path(self.tmp.name) / ".config" / ".jira").mkdir(parents=True) + self.config = Path(self.tmp.name) / ".config" / ".jira" / ".config.yml" + + def api(self, server): + self.config.write_text(f"server: {server}\nlogin: someone@example.com\n") + with mock.patch.object(pc.Path, "home", return_value=Path(self.tmp.name)), \ + mock.patch.dict(pc.os.environ, {"JIRA_API_TOKEN": "token"}): + return pc.jira_api() + + def test_https_is_kept(self): + self.assertEqual( + self.api("https://x.atlassian.net")[0], "https://x.atlassian.net" + ) + + def test_a_bare_host_gets_https(self): + self.assertEqual( + self.api("x.atlassian.net")[0], "https://x.atlassian.net" + ) + + def test_cleartext_http_is_refused_so_the_token_never_leaves(self): + self.assertIsNone(self.api("http://x.atlassian.net")) + + +class ProjectArgumentTest(unittest.TestCase): + def test_a_project_key_is_accepted(self): + self.assertEqual(pc.project_key("HYPERFLEET"), "HYPERFLEET") + + def test_jql_is_not_a_project_key(self): + with self.assertRaises(pc.argparse.ArgumentTypeError): + pc.project_key("HF OR project = SECRET") + + class AskTest(unittest.TestCase): def ask(self, status, days, blockers=None, summary="A large item"): item = { @@ -420,6 +526,37 @@ def test_a_pipe_in_the_summary_does_not_break_the_row(self): row = [line for line in pc.render_text(data).splitlines() if "HYPERFLEET-1)" in line][0] self.assertEqual(row.count("|") - row.count("\\|"), 7) + def test_a_failed_changelog_read_is_named_in_the_report(self): + data = self.data() + data["changelog_signal"] = { + "available": False, + "failed": 2, + "checked": 7, + "status_dates": 5, + "assignments": 3, + } + self.assertIn( + "Signal: partial - 2 of 7 changelog reads failed", pc.render_text(data) + ) + + def test_a_missing_token_is_named_in_the_report(self): + data = self.data() + data["changelog_signal"] = {"available": False, "failed": 0, "checked": 7} + self.assertIn( + "Signal: partial - no JIRA_API_TOKEN", pc.render_text(data) + ) + + def test_a_complete_signal_prints_no_partial_line(self): + data = self.data() + data["changelog_signal"] = { + "available": True, + "failed": 0, + "checked": 7, + "status_dates": 5, + "assignments": 3, + } + self.assertNotIn("Signal: partial", pc.render_text(data)) + class TicketRefTest(unittest.TestCase): base = "https://example.atlassian.net/browse/" diff --git a/hyperfleet-jira/tests/test_sprint_status.py b/hyperfleet-jira/tests/test_sprint_status.py index 019a9ac..795df00 100644 --- a/hyperfleet-jira/tests/test_sprint_status.py +++ b/hyperfleet-jira/tests/test_sprint_status.py @@ -337,5 +337,138 @@ def test_no_base_url_falls_back_to_bare(self): self.assertEqual(ss.ticket_ref("HYPERFLEET-1", None, "markdown"), "HYPERFLEET-1") +class PreviousSprintTest(unittest.TestCase): + rows = [ + {"id": "1", "name": "Sprint 17", "start": "2026-09-01", "end": "2026-09-21", "state": "closed"}, + {"id": "2", "name": "Sprint 18", "start": "2026-09-22", "end": "2026-10-12", "state": "closed"}, + {"id": "3", "name": "Sprint 19", "start": "2026-11-02", "end": "2026-11-22", "state": "closed"}, + ] + + def find(self, before=None): + with mock.patch.object(ss, "sprint_rows", return_value=self.rows): + return ss.previous_sprint("HYPERFLEET", "jira", before) + + def test_without_a_target_the_latest_closed_sprint_wins(self): + self.assertEqual(self.find()["id"], "3") + + def test_a_later_closed_sprint_is_not_a_baseline(self): + found = self.find(before="2026-11-02") + self.assertEqual(found["id"], "2") + + def test_no_earlier_sprint_returns_none(self): + self.assertIsNone(self.find(before="2026-09-01")) + + def test_a_row_with_no_end_date_is_not_a_baseline(self): + rows = [{"id": "9", "name": "Broken", "start": "", "end": "", "state": "closed"}] + with mock.patch.object(ss, "sprint_rows", return_value=rows): + self.assertIsNone(ss.previous_sprint("HYPERFLEET", "jira", "2026-11-02")) + + +class RenderSignalTest(unittest.TestCase): + def data(self): + return { + "sprint": {"name": "Sprint 19", "start": "2026-11-02", "end": "2026-11-22"}, + "totals": { + "by_status": [{"status": "Backlog", "category": "To Do", "items": 1, "sp": 5}], + "items": 1, + "sp": 5, + "percent_by_sp": 0, + "percent_by_items": 0, + "done": {"items": 0, "sp": 0}, + }, + "blockers": { + "blocked": [], + "blocked_items": 0, + "blocked_sp": 0, + "high_priority": [], + "priority_checked": "Major", + "priorities_seen": ["Normal"], + }, + "at_risk": { + "stale": [], + "stale_items": 0, + "stale_days": 5, + "missing_sp_items": 0, + "unassigned_items": 0, + "unassigned_sp": 0, + }, + "carry_over": { + "items": 0, + "sp": 0, + "by_reason": {"unassigned": 0, "stale": 0, "unestimated": 0}, + }, + "capacity": {"available": False, "reason": "no baseline"}, + "workload": [], + "workload_statuses": [], + "notes": { + "movement_basis": "movement basis", + "progress_basis": "progress basis", + "baseline_basis": "baseline basis", + }, + "changelog_signal": {"available": True, "failed": 0, "checked": 1}, + } + + def test_method_names_all_three_bases(self): + text = ss.render_text(self.data()) + for basis in ("movement basis", "progress basis", "baseline basis"): + self.assertIn(basis, text) + + def test_a_failed_changelog_read_is_named_in_the_report(self): + data = self.data() + data["changelog_signal"] = {"available": False, "failed": 2, "checked": 7} + self.assertIn("signal: partial - 2 of 7 changelog reads failed", ss.render_text(data)) + + def test_a_missing_token_is_named_in_the_report(self): + data = self.data() + data["changelog_signal"] = {"available": False, "failed": 0, "checked": 7} + self.assertIn("signal: partial - no JIRA_API_TOKEN", ss.render_text(data)) + + def test_a_complete_signal_prints_no_partial_line(self): + self.assertNotIn("signal: partial", ss.render_text(self.data())) + + +class ChangelogFailureTest(unittest.TestCase): + api = ("https://example.atlassian.net", "auth") + + def item(self): + return { + "key": "HYPERFLEET-1671", + "owner": "Phuongnhat Nguyen", + "assignee_id": "acc-1", + "days_in_status": 47, + "days_since_comment": 13, + "days_without_movement": 13, + } + + def test_a_failed_read_is_counted_not_hidden(self): + with mock.patch.object(ss, "jira_api", return_value=self.api), \ + mock.patch.object( + ss, "changelog_dates", + side_effect=ss.ChangelogUnavailable("HYPERFLEET-1671: HTTPError"), + ): + report = ss.apply_changelog_signals([self.item()], TODAY, 1) + self.assertFalse(report["available"]) + self.assertEqual(report["failed"], 1) + + def test_a_failed_read_leaves_the_clock_alone(self): + subject = self.item() + with mock.patch.object(ss, "jira_api", return_value=self.api), \ + mock.patch.object( + ss, "changelog_dates", side_effect=ss.ChangelogUnavailable("boom") + ): + ss.apply_changelog_signals([subject], TODAY, 1) + self.assertEqual(subject["days_without_movement"], 13) + self.assertIsNone(subject["status_entered"]) + + +class ProjectArgumentTest(unittest.TestCase): + def test_a_project_key_is_accepted(self): + self.assertEqual(ss.project_key("HYPERFLEET"), "HYPERFLEET") + + def test_jql_is_not_a_project_key(self): + with self.assertRaises(ss.argparse.ArgumentTypeError): + ss.project_key("HF OR project = SECRET") + + if __name__ == "__main__": unittest.main() From d03e7b046f4832039b38d5e1cb9c714048d9044d Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 11:44:14 -0300 Subject: [PATCH 3/9] fix(hyperfleet-jira): harden the sprint commands after review - resolve the collector through ${CLAUDE_PLUGIN_ROOT} and drop the ambiguous versioned-cache fallback - keep the user's project argument out of shell source and validate it first - require one table row per item instead of merging owners - render the partial-signal notice from JSON, and widen the changelog failure filter to HTTP and decode errors - refuse redirects so the Basic auth token stays on the Jira host - count a changelog capped by Jira as a failed read - fix the 5 SP wording, carry-over reason counts and README claims - add direct tests for the HTTPS guard and changelog error mapping --- hyperfleet-jira/README.md | 4 +- .../commands/sprint-pulse-check.md | 15 +-- hyperfleet-jira/commands/sprint-status.md | 14 +-- hyperfleet-jira/scripts/pulse_check.py | 39 ++++++- hyperfleet-jira/scripts/sprint_status.py | 39 ++++++- hyperfleet-jira/tests/test_pulse_check.py | 80 +++++++++++++- hyperfleet-jira/tests/test_sprint_status.py | 103 ++++++++++++++++++ 7 files changed, 264 insertions(+), 30 deletions(-) diff --git a/hyperfleet-jira/README.md b/hyperfleet-jira/README.md index 91cb4bd..bc4bc7b 100644 --- a/hyperfleet-jira/README.md +++ b/hyperfleet-jira/README.md @@ -11,7 +11,7 @@ A Claude Code plugin that integrates JIRA with your development workflow using [ ### For Team Leads - **`/sprint-status`** - Comprehensive sprint health overview -- **`/sprint-pulse-check`** - Twice-weekly nudge queue for large work items (5 and 8 SP) +- **`/sprint-pulse-check`** - Twice-weekly nudge queue for large work items (5 SP and above) - **`/team-weekly-update`** - Weekly team progress report grouped by activity type and epic - **`/triage`** - Audit tickets for missing fields and quality issues @@ -127,7 +127,7 @@ Output includes: - Progress by status, by story points and by item count - Blocked items, highest-priority open items, and stale in-progress work - Team workload distribution, including unassigned work -- Carry-over candidates and a capacity projection from the previous sprint's pace +- Carry-over totals (items, story points, and reasons) and a capacity projection from the previous sprint's pace The numbers come from `scripts/sprint_status.py` (`--format json` or the rendered `--format markdown`), not from hand-written JQL: story points need `issue view --raw`, and `issue list` truncates at 100 issues without saying so. diff --git a/hyperfleet-jira/commands/sprint-pulse-check.md b/hyperfleet-jira/commands/sprint-pulse-check.md index 6fc7755..a866da8 100644 --- a/hyperfleet-jira/commands/sprint-pulse-check.md +++ b/hyperfleet-jira/commands/sprint-pulse-check.md @@ -1,12 +1,12 @@ --- -description: Pulse check on large work items (5 and 8 SP) - the nudge queue leads work through twice a week +description: Pulse check on large work items (5 SP and above) - the nudge queue leads work through twice a week allowed-tools: Bash argument-hint: [project-key] --- # Sprint Pulse Check -Leads run a pulse check a couple of times per week during a sprint on the large items (5 and 8 SP), to find out whether the owner needs help or has open questions. The agreement behind it: work over 5 story points needs shared context, and a reviewer cannot reconstruct that context from a merged PR. +Leads run a pulse check a couple of times per week during a sprint on the large items (5 SP and above), to find out whether the owner needs help or has open questions. The agreement behind it: work at 5 story points and above needs shared context, and a reviewer cannot reconstruct that context from a merged PR. This command produces a short nudge queue. It is not a sprint status report: it does not compute progress, and it does not summarize the sprint. For that, use `/sprint-status`. @@ -18,8 +18,7 @@ This command produces a short nudge queue. It is not a sprint status report: it 1. **Locate the collector script.** It ships with this command in the plugin. No globs: an unmatched glob aborts the shell in zsh. ```bash PULSE="" - for root in "$CLAUDE_PLUGIN_ROOT" \ - "$HOME/.claude/plugins/cache/hyperfleet-claude-plugins/hyperfleet-jira" \ + for root in "${CLAUDE_PLUGIN_ROOT}" \ "$HOME/.claude/plugins/marketplaces/hyperfleet-claude-plugins/hyperfleet-jira"; do [ -n "$root" ] || continue found=$(find "$root" -maxdepth 3 -name pulse_check.py -type f 2>/dev/null | head -1) @@ -29,10 +28,9 @@ This command produces a short nudge queue. It is not a sprint status report: it ``` If `$PULSE` is empty, stop and say so. The script is the command: do not reimplement the calculation inline. -2. **Run it.** Set `PROJECT` to `$1` when the user gave a project key, and leave it unset otherwise; the script rejects anything that is not a Jira project key. +2. **Run it.** Claude Code substitutes `$1` into this command as text, so never paste it into shell source: a value such as `$(id)` would run. Accept the argument only when it matches `^[A-Z][A-Z0-9_]{1,9}$`; otherwise stop and say it is not a Jira project key. When it matches, use that key in place of `HYPERFLEET` below. ```bash - PROJECT="$1" - python3 "$PULSE" --project "${PROJECT:-HYPERFLEET}" --format json + python3 "$PULSE" --project HYPERFLEET --format json ``` Options: `--today YYYY-MM-DD` for a reproducible run, `--format text` for a ready-to-paste block, `--min-sp` and `--max-rows` to move the thresholds, `--link-style markdown|slack|bare` to match the destination, `--next-pulse YYYY-MM-DD` to print the next scheduled pulse (omit it when the lead has not scheduled one, and the output says "to be scheduled"). @@ -43,7 +41,6 @@ This command produces a short nudge queue. It is not a sprint status report: it 4. **Sharpen the ask.** Each queue item carries a default `ask` derived from the ladder. Rewrite it only when you have concrete context the script cannot have - which reviewer to pull in, which blocker just closed, which decision stalled. Keep it to one line. 5. **Apply the courtesies the script cannot:** - - merge two rows from the same owner when the ask is identical - never promote an item the script left out of the queue (below `--action-after` days) - when an item is `Review`, the ask names reviewers, not the owner - when the item is blocked, the ask names the blocker, never the person holding the ticket @@ -108,10 +105,10 @@ Rules for the output: - **The verb comes from a closed set:** `ask` (approve/reject, status, start or drop), `assign`, `post`, `start`, `propose` (a split), `confirm` (a date). A closed set keeps the column scannable and countable, and it bounds the hand rewrite in step 4 to the specifics - who, which PR, which blocker - never to the choice of action. - **Never restate the item's own age in the Ask.** It is in the `Status · age` cell beside it; repeating it costs width and produces "20+ days: 20+ days". A blocker's age does appear, because that clock is not in the table. - **The verb follows the state, not the age alone:** blocked items name the blocker's move, `Review` asks a reviewer for a decision, `In Progress` asks for evidence on the ticket, and unstarted work asks for a date; a spike asks for the decision note, never for a start date. -- Do not repeat the same owner across rows if two items have the same ask - merge them into one row. - Items in good standing stay visible only in the single "No action" line, never as table rows. - In the `Status · age` cell, `(assigned MM-DD)` marks a clock shortened by a reassignment and `(since MM-DD)` marks a Backlog item with no start. Never show both. - A blocker's age is its own last workflow transition, not the blocked item's. A blocker in `Review` leads the ask and names its reviewer (`Ask Martin to approve or reject HYPERFLEET-1636 (Review 7d)`); an unowned blocker becomes `assign HYPERFLEET-1523`, because there is nobody to ask. +- **Say when the signal is partial.** The command reads JSON, so the script's own text warning never appears. If `changelog_signal.failed` is non-zero, add one line under the queue: `Signal: partial - N of M changelog reads failed; those items use the status category date`. If `changelog_signal.available` is false, add: `Signal: partial - no JIRA_API_TOKEN, so movement ignores exact status changes and assignments`. - State the movement definition in every output. Without it the numbers start arguments. - Date the output, and print the next pulse date, so a stale copy is recognizable at a glance. diff --git a/hyperfleet-jira/commands/sprint-status.md b/hyperfleet-jira/commands/sprint-status.md index 0d92493..f9fe434 100644 --- a/hyperfleet-jira/commands/sprint-status.md +++ b/hyperfleet-jira/commands/sprint-status.md @@ -16,8 +16,7 @@ Comprehensive sprint health report for team leads and scrum masters. 1. **Locate the collector script.** It ships with this command in the plugin. No globs: an unmatched glob aborts the shell in zsh. ```bash SPRINT="" - for root in "$CLAUDE_PLUGIN_ROOT" \ - "$HOME/.claude/plugins/cache/hyperfleet-claude-plugins/hyperfleet-jira" \ + for root in "${CLAUDE_PLUGIN_ROOT}" \ "$HOME/.claude/plugins/marketplaces/hyperfleet-claude-plugins/hyperfleet-jira"; do [ -n "$root" ] || continue found=$(find "$root" -maxdepth 3 -name sprint_status.py -type f 2>/dev/null | head -1) @@ -27,10 +26,9 @@ Comprehensive sprint health report for team leads and scrum masters. ``` If `$SPRINT` is empty, stop and say so. The script is the command: do not fall back to hand-written JQL. -2. **Run it.** Set `PROJECT` to `$1` when the user gave a project key, and leave it unset otherwise; the script rejects anything that is not a Jira project key. +2. **Run it.** Claude Code substitutes `$1` into this command as text, so never paste it into shell source: a value such as `$(id)` would run. Accept the argument only when it matches `^[A-Z][A-Z0-9_]{1,9}$`; otherwise stop and say it is not a Jira project key. When it matches, use that key in place of `HYPERFLEET` below. ```bash - PROJECT="$1" - python3 "$SPRINT" --project "${PROJECT:-HYPERFLEET}" --format markdown + python3 "$SPRINT" --project HYPERFLEET --format markdown ``` Options: `--today YYYY-MM-DD` for a reproducible run, `--sprint ` to report on a sprint other than the active one, `--stale-days` to move the staleness threshold, `--blocker-priority` to change which priority counts as top, `--link-style markdown|slack|bare` to match the destination, `--no-baseline` to skip the previous sprint lookup. @@ -46,7 +44,7 @@ Comprehensive sprint health report for team leads and scrum masters. Three definitions matter when you read it: - **Progress** is shown twice, by story points and by item count. The bar and the headline percentage use story points. Say which one you are quoting. - - **Movement** is the most recent of the exact last status change, the last human comment and the assignment to the current owner. The status and assignment parts need `JIRA_API_TOKEN`; without it the report falls back to `statusCategoryChangedDate` and comments only, so an item can look older than it is. + - **Movement** is the most recent of the exact last status change, the last human comment and the assignment to the current owner. The status and assignment parts need `JIRA_API_TOKEN`; without it the report falls back to `statusCategoryChangedDate` and comments only, so an item can look older than it is. A failed or unavailable changelog read adds a `signal: partial` line to the Method section; keep that line in the report. - **Capacity** is a projection from the previous sprint's pace, not a commitment. At the start of a sprint it is mostly noise; from mid-sprint on it is the number to argue with. 5. **Add Recommendations.** The script cannot write these: they need a decision. @@ -55,7 +53,7 @@ Comprehensive sprint health report for team leads and scrum masters. - Order by what unblocks the most work: an unassigned item that blocks seven others outranks an unassigned item that blocks none. - When the `Blocked by open work` list is long, recommend clearing the blockers rather than chasing the blocked items. The blocked owners cannot move. - Never recommend "add more people" without naming the item and the person. - - For large work items (5 and 8 SP), point the lead to `/sprint-pulse-check` instead of expanding this report. + - For large work items (5 SP and above), point the lead to `/sprint-pulse-check` instead of expanding this report. 6. **Keep the report in English.** The chat reply that accompanies it follows the user's language. @@ -122,7 +120,7 @@ Progress: [=====> ] X% by SP (X of X) | X% by count (X of X) ### Carry-Over and Capacity ```text -Needs a decision: X items / X SP (X unassigned, X stale, X unestimated; a ticket can be listed twice) +Needs a decision: X items / X SP (X unassigned, X stale, X unestimated; a ticket can be counted in multiple reasons) Capacity: X SP remaining; at the previous sprint's pace the team delivers X SP in the X days left (X SP over capacity, or X SP of headroom) ``` diff --git a/hyperfleet-jira/scripts/pulse_check.py b/hyperfleet-jira/scripts/pulse_check.py index 3a55ed3..bc92a25 100755 --- a/hyperfleet-jira/scripts/pulse_check.py +++ b/hyperfleet-jira/scripts/pulse_check.py @@ -29,6 +29,7 @@ import argparse import base64 +import http.client import json import os import re @@ -156,6 +157,18 @@ def jira_api() -> tuple[str, str] | None: return base, auth +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse redirects: urllib copies the Authorization header to the target.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp) + + +def open_changelog(request: urllib.request.Request): + """GET that never follows a redirect, so the token stays on the Jira host.""" + return urllib.request.build_opener(NoRedirect).open(request, timeout=15) + + def changelog_dates( key: str, account_id: str | None, api: tuple[str, str] | None ) -> tuple[date | None, date | None]: @@ -179,14 +192,34 @@ def changelog_dates( url, headers={"Authorization": f"Basic {auth}", "Accept": "application/json"} ) try: - with urllib.request.urlopen(request, timeout=15) as response: + with open_changelog(request) as response: payload = json.load(response) - except (urllib.error.URLError, OSError, json.JSONDecodeError) as exc: + except ( + urllib.error.URLError, + http.client.HTTPException, + OSError, + ValueError, + ) as exc: + # HTTPError is a URLError and JSONDecodeError/UnicodeDecodeError are + # ValueErrors: every transport or decode failure is one counted failure. raise ChangelogUnavailable(f"{key}: {type(exc).__name__}") from exc + changelog = payload.get("changelog") or {} + histories = changelog.get("histories") or [] + try: + total = int(changelog.get("total") or 0) + except (TypeError, ValueError): + total = 0 + if total > len(histories): + # The inline changelog is capped; a truncated read can miss the exact + # transition, so it must be counted instead of looking like "no entry". + raise ChangelogUnavailable( + f"{key}: changelog truncated ({len(histories)} of {total} entries)" + ) + status_dates: list[date] = [] assignment_dates: list[date] = [] - for entry in (payload.get("changelog") or {}).get("histories") or []: + for entry in histories: changed_status = changed_assignee = False for change in entry.get("items") or []: if change.get("field") == "status": diff --git a/hyperfleet-jira/scripts/sprint_status.py b/hyperfleet-jira/scripts/sprint_status.py index b468789..25c480b 100755 --- a/hyperfleet-jira/scripts/sprint_status.py +++ b/hyperfleet-jira/scripts/sprint_status.py @@ -35,6 +35,7 @@ import argparse import base64 +import http.client import json import os import re @@ -607,6 +608,18 @@ def jira_api() -> tuple[str, str] | None: return base, auth +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse redirects: urllib copies the Authorization header to the target.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp) + + +def open_changelog(request: urllib.request.Request): + """GET that never follows a redirect, so the token stays on the Jira host.""" + return urllib.request.build_opener(NoRedirect).open(request, timeout=15) + + def changelog_dates( key: str, account_id: str | None, api: tuple[str, str] | None ) -> tuple[date | None, date | None]: @@ -630,14 +643,34 @@ def changelog_dates( url, headers={"Authorization": f"Basic {auth}", "Accept": "application/json"} ) try: - with urllib.request.urlopen(request, timeout=15) as response: + with open_changelog(request) as response: payload = json.load(response) - except (urllib.error.URLError, OSError, json.JSONDecodeError) as exc: + except ( + urllib.error.URLError, + http.client.HTTPException, + OSError, + ValueError, + ) as exc: + # HTTPError is a URLError and JSONDecodeError/UnicodeDecodeError are + # ValueErrors: every transport or decode failure is one counted failure. raise ChangelogUnavailable(f"{key}: {type(exc).__name__}") from exc + changelog = payload.get("changelog") or {} + histories = changelog.get("histories") or [] + try: + total = int(changelog.get("total") or 0) + except (TypeError, ValueError): + total = 0 + if total > len(histories): + # The inline changelog is capped; a truncated read can miss the exact + # transition, so it must be counted instead of looking like "no entry". + raise ChangelogUnavailable( + f"{key}: changelog truncated ({len(histories)} of {total} entries)" + ) + status_dates: list[date] = [] assignment_dates: list[date] = [] - for entry in (payload.get("changelog") or {}).get("histories") or []: + for entry in histories: changed_status = changed_assignee = False for change in entry.get("items") or []: if change.get("field") == "status": diff --git a/hyperfleet-jira/tests/test_pulse_check.py b/hyperfleet-jira/tests/test_pulse_check.py index d5c8d19..8e863ab 100644 --- a/hyperfleet-jira/tests/test_pulse_check.py +++ b/hyperfleet-jira/tests/test_pulse_check.py @@ -228,7 +228,7 @@ def histories(self): def test_changelog_returns_the_latest_status_and_assignment(self): with mock.patch.object( - pc.urllib.request, "urlopen", return_value=self.Response(self.histories()) + pc, "open_changelog", return_value=self.Response(self.histories()) ): self.assertEqual( pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), @@ -245,7 +245,7 @@ def test_new_to_backlog_is_classification_not_movement(self): } } with mock.patch.object( - pc.urllib.request, "urlopen", return_value=self.Response(payload) + pc, "open_changelog", return_value=self.Response(payload) ): self.assertEqual( pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (None, None) @@ -254,7 +254,7 @@ def test_new_to_backlog_is_classification_not_movement(self): def test_created_in_status_has_no_transition_date(self): payload = {"changelog": {"histories": []}} with mock.patch.object( - pc.urllib.request, "urlopen", return_value=self.Response(payload) + pc, "open_changelog", return_value=self.Response(payload) ): self.assertEqual( pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (None, None) @@ -312,14 +312,84 @@ def test_a_failed_read_leaves_the_clock_alone(self): def test_an_http_error_raises_instead_of_looking_empty(self): with mock.patch.object( - pc.urllib.request, - "urlopen", + pc, + "open_changelog", side_effect=pc.urllib.error.URLError("401 Unauthorized"), ): with self.assertRaises(pc.ChangelogUnavailable): pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) +class ChangelogTransportTest(unittest.TestCase): + api = ("https://example.atlassian.net", "auth") + + class Response: + def __init__(self, payload): + self.payload = payload + + def __enter__(self): + return io.StringIO(json.dumps(self.payload)) + + def __exit__(self, *exc): + return False + + def call(self, payload=None, error=None): + if error is not None: + patcher = mock.patch.object(pc, "open_changelog", side_effect=error) + else: + patcher = mock.patch.object( + pc, "open_changelog", return_value=self.Response(payload) + ) + with patcher: + return pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) + + def test_a_truncated_response_is_counted(self): + with self.assertRaises(pc.ChangelogUnavailable): + self.call(error=pc.http.client.IncompleteRead(b"")) + + def test_a_non_utf8_body_is_counted(self): + error = UnicodeDecodeError("utf-8", b"", 0, 1, "invalid start byte") + with self.assertRaises(pc.ChangelogUnavailable): + self.call(error=error) + + def test_a_capped_changelog_is_counted(self): + with self.assertRaises(pc.ChangelogUnavailable): + self.call(payload={"changelog": {"total": 150, "histories": []}}) + + def test_a_complete_changelog_is_read(self): + payload = { + "changelog": { + "total": 1, + "histories": [ + { + "created": "2026-10-30T10:00:00.000+0000", + "items": [ + { + "field": "status", + "fromString": "In Progress", + "toString": "Review", + } + ], + } + ], + } + } + self.assertEqual(self.call(payload=payload)[0], date(2026, 10, 30)) + + def test_a_redirect_is_refused(self): + handler = pc.NoRedirect() + with self.assertRaises(pc.urllib.error.HTTPError) as caught: + handler.redirect_request( + pc.urllib.request.Request("https://a.example"), + None, + 302, + "Found", + {}, + "https://b.example", + ) + caught.exception.close() + + class RunJiraTest(unittest.TestCase): def test_a_timeout_is_a_pulse_error(self): with mock.patch.object( diff --git a/hyperfleet-jira/tests/test_sprint_status.py b/hyperfleet-jira/tests/test_sprint_status.py index 795df00..2c547de 100644 --- a/hyperfleet-jira/tests/test_sprint_status.py +++ b/hyperfleet-jira/tests/test_sprint_status.py @@ -10,7 +10,11 @@ the movement signal that counts automation comments as activity. """ +import io +import json +import os import sys +import tempfile import unittest from datetime import date from pathlib import Path @@ -461,6 +465,105 @@ def test_a_failed_read_leaves_the_clock_alone(self): self.assertIsNone(subject["status_entered"]) +class JiraApiGuardTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + (Path(self.tmp.name) / ".config" / ".jira").mkdir(parents=True) + self.config = Path(self.tmp.name) / ".config" / ".jira" / ".config.yml" + + def api(self, server): + self.config.write_text(f"server: {server}\nlogin: someone@example.com\n") + with mock.patch.object(ss.Path, "home", return_value=Path(self.tmp.name)), \ + mock.patch.dict(os.environ, {"JIRA_API_TOKEN": "token"}): + return ss.jira_api() + + def test_https_is_kept(self): + self.assertEqual( + self.api("https://x.atlassian.net")[0], "https://x.atlassian.net" + ) + + def test_a_bare_host_gets_https(self): + self.assertEqual(self.api("x.atlassian.net")[0], "https://x.atlassian.net") + + def test_cleartext_http_is_refused(self): + self.assertIsNone(self.api("http://x.atlassian.net")) + + +class ChangelogTransportTest(unittest.TestCase): + api = ("https://example.atlassian.net", "auth") + + class Response: + def __init__(self, payload): + self.payload = payload + + def __enter__(self): + return io.StringIO(json.dumps(self.payload)) + + def __exit__(self, *exc): + return False + + def call(self, payload=None, error=None): + if error is not None: + patcher = mock.patch.object(ss, "open_changelog", side_effect=error) + else: + patcher = mock.patch.object( + ss, "open_changelog", return_value=self.Response(payload) + ) + with patcher: + return ss.changelog_dates("HYPERFLEET-1", "acc-1", self.api) + + def test_a_network_error_is_counted(self): + with self.assertRaises(ss.ChangelogUnavailable): + self.call(error=ss.urllib.error.URLError("401 Unauthorized")) + + def test_a_truncated_response_is_counted(self): + with self.assertRaises(ss.ChangelogUnavailable): + self.call(error=ss.http.client.IncompleteRead(b"")) + + def test_a_non_utf8_body_is_counted(self): + error = UnicodeDecodeError("utf-8", b"", 0, 1, "invalid start byte") + with self.assertRaises(ss.ChangelogUnavailable): + self.call(error=error) + + def test_a_capped_changelog_is_counted(self): + with self.assertRaises(ss.ChangelogUnavailable): + self.call(payload={"changelog": {"total": 150, "histories": []}}) + + def test_a_complete_changelog_is_read(self): + payload = { + "changelog": { + "total": 1, + "histories": [ + { + "created": "2026-10-30T10:00:00.000+0000", + "items": [ + { + "field": "status", + "fromString": "In Progress", + "toString": "Review", + } + ], + } + ], + } + } + self.assertEqual(self.call(payload=payload)[0], date(2026, 10, 30)) + + def test_a_redirect_is_refused(self): + handler = ss.NoRedirect() + with self.assertRaises(ss.urllib.error.HTTPError) as caught: + handler.redirect_request( + ss.urllib.request.Request("https://a.example"), + None, + 302, + "Found", + {}, + "https://b.example", + ) + caught.exception.close() + + class ProjectArgumentTest(unittest.TestCase): def test_a_project_key_is_accepted(self): self.assertEqual(ss.project_key("HYPERFLEET"), "HYPERFLEET") From 20c2a133958416fd1c7da257f4785cbaae57b2cd Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 14:52:19 -0300 Subject: [PATCH 4/9] HYPERFLEET-1890 - fix(hyperfleet-jira): share the Jira layer and measure the baseline at sprint end Extract scripts/jira_common.py so the two commands cannot drift again: one pager, one changelog reader, one definition of Done (statusCategory, never a status name). pulse_check now filters large items with statusCategory != Done instead of status != Closed, and open blockers/dependants use the same category rule, with an unread target counting as open. Count baseline delivery at the previous sprint's end: work closed during the current sprint no longer inflates the baseline or the capacity projection, and the report prints the cutoff date. Tests follow the helpers to jira_common and cover the baseline cutoff, the category filter and open_links. 108 tests pass. --- hyperfleet-jira/commands/sprint-status.md | 4 +- hyperfleet-jira/scripts/jira_common.py | 563 ++++++++++++++++++++ hyperfleet-jira/scripts/pulse_check.py | 432 ++------------- hyperfleet-jira/scripts/sprint_status.py | 551 +++---------------- hyperfleet-jira/tests/test_pulse_check.py | 107 ++-- hyperfleet-jira/tests/test_sprint_status.py | 108 +++- 6 files changed, 808 insertions(+), 957 deletions(-) create mode 100644 hyperfleet-jira/scripts/jira_common.py diff --git a/hyperfleet-jira/commands/sprint-status.md b/hyperfleet-jira/commands/sprint-status.md index f9fe434..36a4421 100644 --- a/hyperfleet-jira/commands/sprint-status.md +++ b/hyperfleet-jira/commands/sprint-status.md @@ -32,7 +32,7 @@ Comprehensive sprint health report for team leads and scrum masters. ``` Options: `--today YYYY-MM-DD` for a reproducible run, `--sprint ` to report on a sprint other than the active one, `--stale-days` to move the staleness threshold, `--blocker-priority` to change which priority counts as top, `--link-style markdown|slack|bare` to match the destination, `--no-baseline` to skip the previous sprint lookup. - The script reads the sprint metadata and goal, every issue in the sprint, the story points, the movement signals, the open blockers, the previous sprint's baseline, and a capacity projection. It returns the report in one document. + The script reads the sprint metadata and goal, every issue in the sprint, the story points, the movement signals, the open blockers, the previous sprint's baseline, and a capacity projection. The baseline's delivered points are measured at the previous sprint's end date, so work closed later is not credited to it. It returns the report in one document. 3. **Do not recompute by hand, and do not re-query Jira.** These four queries look right and return wrong answers: - `status = Done`, `status = 'To Do'`, `priority = Highest`, `priority = High` match nothing in HYPERFLEET, which uses `Backlog` / `In Progress` / `Review` / `Closed` and `Major` / `Normal`. Use status categories, which the script does. @@ -88,7 +88,7 @@ Sprint: [Sprint Name] Goal: [Sprint Goal] Duration: [Start Date] - [End Date] (N days) Days Remaining: X days -Previous sprint baseline: X SP committed / X SP delivered (X%) across N items +Previous sprint baseline: X SP committed / X SP delivered by [End Date] (X%) across N items Scope: X SP committed vs X SP delivered in the previous sprint (+/-X%) Jira: https:///browse/ ``` diff --git a/hyperfleet-jira/scripts/jira_common.py b/hyperfleet-jira/scripts/jira_common.py new file mode 100644 index 0000000..8969f8c --- /dev/null +++ b/hyperfleet-jira/scripts/jira_common.py @@ -0,0 +1,563 @@ +#!/usr/bin/env python3 +"""Shared jira-cli and Jira REST layer for the sprint commands. + +`/sprint-status` and `/sprint-pulse-check` read the same objects: sprints, issues, +story points, links, comments and the changelog. Keeping two copies of that code +is how the two commands drifted apart in review - one filtered `status != Closed` +while the other used the status category, and the two disagree as soon as a +project names its done status something else (HYPERFLEET has no `Closed`). + +So the Jira plumbing lives here once. A script imports what it needs, and a rule +such as "work is Done by category, never by status name" has exactly one +definition. `JiraError` is also shared: each script aliases it to its own name so +existing call sites and tests keep reading naturally. + +Read-only. Nothing here writes to Jira. +""" + +from __future__ import annotations + +import argparse +import base64 +import http.client +import json +import os +import re +import subprocess +import sys +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from datetime import date, datetime +from pathlib import Path + + +class JiraError(Exception): + """A jira-cli invocation or a Jira read failed.""" + + +class ChangelogUnavailable(Exception): + """A changelog read failed; it must not be read as "no entry".""" + + +# Jira groups statuses into three categories; the category is the stable answer, +# the status name is project-specific. HYPERFLEET has no `Done` or `Closed` +# status, so every "is this finished?" check must read the category. +DONE_CATEGORY = "Done" +CATEGORY_ORDER = {"To Do": 0, "In Progress": 1, DONE_CATEGORY: 2} + +# This is the one JQL fragment for "still open". `status != Closed` matches +# nothing in HYPERFLEET and would silently include finished work. +OPEN_STATUS_JQL = f"statusCategory != {DONE_CATEGORY}" + +# A move between these statuses is classification, not work. HYPERFLEET creates +# issues in `New`; a bulk New -> Backlog sweep must not reset the movement clock. +TRIVIAL_STATUSES = {"New", "Backlog"} + + +def status_category(doc: dict) -> str: + """The status category of an issue document: To Do, In Progress or Done.""" + status = doc["fields"].get("status") or {} + return ((status.get("statusCategory") or {}).get("name") or "").strip() + + +def status_name(doc: dict) -> str: + return ((doc["fields"].get("status") or {}).get("name") or "").strip() + + +def is_done_doc(doc: dict) -> bool: + return status_category(doc) == DONE_CATEGORY + + +def open_links(keys: list[str], category_of: dict[str, str]) -> list[str]: + """Link targets that are still open work. + + A target with no known category counts as open: an unread link is not + evidence that the blocker is gone. + """ + return [key for key in keys if category_of.get(key) != DONE_CATEGORY] + + +def status_change_counts(change: dict) -> bool: + """True when a status transition is workflow movement, not classification.""" + from_status = (change.get("fromString") or "").strip() + to_status = (change.get("toString") or "").strip() + return not (from_status in TRIVIAL_STATUSES and to_status in TRIVIAL_STATUSES) + + +# -------------------------------------------------------------------------- +# jira-cli plumbing +# -------------------------------------------------------------------------- + + +def run_jira(args: list[str], binary: str) -> str: + try: + proc = subprocess.run( + [binary, *args], capture_output=True, text=True, timeout=120 + ) + except (subprocess.TimeoutExpired, FileNotFoundError) as exc: + raise JiraError(f"jira {' '.join(args[:2])} could not run: {exc}") from exc + if proc.returncode != 0: + raise JiraError( + f"jira {' '.join(args)} failed ({proc.returncode}): " + f"{(proc.stderr or proc.stdout).strip()[:300]}" + ) + return proc.stdout + + +def parse_date(value: str) -> date: + return datetime.strptime(value[:10], "%Y-%m-%d").date() + + +def key_number(key: str) -> int: + _, _, number = key.rpartition("-") + return int(number) + + +def jql_project(project: str) -> str: + return f"project = {project}" + + +def search_keys(jql: str, project: str, binary: str, limit: int = 100) -> list[str]: + """List every key matching `jql`, past the 100-issue page cap. + + `jira issue list --paginate :` ignores ``: every page + returns the same first N issues. It also rejects a limit above 100. So the + only way to walk a larger result is to move the search window with JQL + itself, using the lowest key of each batch as the next boundary. + + An incomplete result raises instead of looking like a complete one. + """ + keys: list[str] = [] + seen: set[str] = set() + boundary: str | None = None + + for _ in range(200): + query = jql if boundary is None else f"({jql}) AND key < {boundary}" + out = run_jira( + [ + "issue", "list", "-q", query, "-p", project, + "--plain", "--no-headers", "--columns", "KEY", + "--order-by", "key", "--paginate", f"0:{limit}", + ], + binary, + ) + batch = [line.strip() for line in out.splitlines() if line.strip()] + fresh = [key for key in batch if key not in seen] + if not fresh: + return keys + keys.extend(fresh) + seen.update(fresh) + if len(batch) < limit: + return keys + boundary = min(batch, key=key_number) + + raise JiraError( + f"gave up paging after 200 batches ({len(keys)} keys); narrow the JQL" + ) + + +def sprint_rows(project: str, state: str, binary: str) -> list[dict]: + out = run_jira( + [ + "sprint", "list", "-p", project, "--state", state, + "--plain", "--no-truncate", + "--columns", "ID,NAME,START,END,STATE", + ], + binary, + ) + lines = [line for line in out.strip().splitlines() if line.strip()] + rows = [] + for line in lines[1:]: + sid, name, start, end, sprint_state = (line.split("\t") + [""] * 5)[:5] + rows.append( + { + "id": sid.strip(), + "name": name.strip(), + "start": start.strip()[:10], + "end": end.strip()[:10], + "state": sprint_state.strip(), + } + ) + return rows + + +def active_sprint(project: str, binary: str) -> dict: + rows = sprint_rows(project, "active", binary) + if not rows: + raise JiraError(f"no active sprint found for project {project}") + if len(rows) > 1: + print(f"warning: {len(rows)} active sprints; using {rows[0]['name']}", file=sys.stderr) + return rows[0] + + +def fetch_issue(key: str, project: str, binary: str) -> dict: + try: + return json.loads( + run_jira(["issue", "view", key, "-p", project, "--raw"], binary) + ) + except (JiraError, json.JSONDecodeError) as exc: + raise JiraError(f"could not read {key}: {exc}") from exc + + +def fetch_all(keys: list[str], project: str, binary: str, jobs: int) -> dict[str, dict]: + unique = sorted(set(keys), key=key_number) + with ThreadPoolExecutor(max_workers=jobs) as pool: + docs = list(pool.map(lambda key: fetch_issue(key, project, binary), unique)) + return {doc["key"]: doc for doc in docs} + + +# -------------------------------------------------------------------------- +# Issue shape +# -------------------------------------------------------------------------- + + +def link_targets(doc: dict) -> tuple[list[str], list[str]]: + """Return (blocked_by, blocks) keys from the issue links. + + Jira labels every Blocks link with inward="is blocked by" and + outward="blocks", so the type label alone cannot tell you the direction. + What decides is which side of the link carries the other issue. + """ + blocked_by, blocks = [], [] + for link in doc["fields"].get("issuelinks") or []: + kind = link.get("type") or {} + inward, outward = link.get("inwardIssue"), link.get("outwardIssue") + if ( + inward + and inward.get("key") + and (kind.get("inward") or "").strip().lower() == "is blocked by" + ): + blocked_by.append(inward["key"]) + elif ( + outward + and outward.get("key") + and (kind.get("outward") or "").strip().lower() == "blocks" + ): + blocks.append(outward["key"]) + return blocked_by, blocks + + +def human_comment_dates(doc: dict) -> list[date]: + """Comment dates written by people, not integrations. + + Jira automation comments (`author.accountType == "app"`) are not movement: + a ticket whose only recent comment came from "Automation for Jira" was not + touched by anyone. + """ + dates = [] + for comment in (doc["fields"].get("comment") or {}).get("comments") or []: + author = comment.get("author") or {} + if author.get("accountType") == "app": + continue + created = comment.get("created") + if created: + dates.append(parse_date(created)) + return dates + + +def describe(key: str, doc: dict, sp_field: str, today: date) -> dict: + """The fields both reports need, read once. + + `status_changed` is the category change date, which is a fallback clock: it + only moves between To Do / In Progress / Done. It is also the close date of a + Done item, so the baseline uses it to tell work finished inside the previous + sprint from work finished later while the sprint sat in the backlog. + + `sp` stays None when the field is empty: "no estimate" and "zero points" are + different facts, and only the caller knows which one it can treat as zero. + """ + fields = doc["fields"] + status = fields.get("status") or {} + category = ((status.get("statusCategory") or {}).get("name") or "").strip() + status_changed = parse_date(fields["statuscategorychangedate"]) + comments = human_comment_dates(doc) + last_comment = max(comments) if comments else None + days_in_status = (today - status_changed).days + days_since_comment = (today - last_comment).days if last_comment else None + signals = [days_in_status] + if days_since_comment is not None: + signals.append(days_since_comment) + blocked_by, blocks = link_targets(doc) + points = fields.get(sp_field) + + return { + "key": key, + "summary": (fields.get("summary") or "").strip(), + "type": (fields.get("issuetype") or {}).get("name", ""), + "sp": points if isinstance(points, (int, float)) else None, + "owner": ((fields.get("assignee") or {}).get("displayName") or "").strip(), + "assignee_id": (fields.get("assignee") or {}).get("accountId") or None, + "status": (status.get("name") or "").strip(), + "category": category, + "priority": (fields.get("priority") or {}).get("name", ""), + "epic": (fields.get("parent") or {}).get("key"), + "labels": fields.get("labels") or [], + "created": (fields.get("created") or "")[:10], + "status_changed": status_changed.isoformat(), + "days_in_status": days_in_status, + "days_since_comment": days_since_comment, + "days_without_movement": min(signals), + "last_comment": last_comment.isoformat() if last_comment else None, + "blocked_by": blocked_by, + "blocks": blocks, + "is_done": category == DONE_CATEGORY, + } + + +# -------------------------------------------------------------------------- +# Linking and rendering +# -------------------------------------------------------------------------- + + +def jira_base_url() -> str | None: + """Read the server from the jira-cli config, so no report hardcodes it. + + Bare keys are only resolvable if the reader knows the server; one line here + saves every table from carrying a link per row. + """ + config = Path.home() / ".config" / ".jira" / ".config.yml" + try: + text = config.read_text() + except OSError: + return None + match = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) + if not match: + return None + server = match.group(1).rstrip("/") + if "://" not in server: + server = f"https://{server}" + if not server.startswith("https://"): + return None + return f"{server}/browse/" + + +def ticket_ref(key: str, base_url: str | None, style: str) -> str: + """Render a ticket key for the destination. + + The same report is pasted into the TUI, Slack and log files, and only one of + the three understands `[text](url)`. Keep the syntax switchable instead of + guessing at render time. + """ + if not base_url or style == "bare": + return key + url = f"{base_url}{key}" + if style == "slack": + return f"<{url}|{key}>" + return f"[{key}]({url})" + + +# -------------------------------------------------------------------------- +# Changelog (Jira REST, the only place exact transitions live) +# -------------------------------------------------------------------------- + + +def jira_api() -> tuple[str, str] | None: + """(server, basic-auth header) for Jira's REST API, or None. + + The changelog is the only place Jira records the exact status transition and + the owner change, and jira-cli exposes neither. The token is the same + `JIRA_API_TOKEN` the CLI uses; without it both signals are unavailable and the + scripts fall back to `statusCategoryChangedDate`. + """ + token = os.environ.get("JIRA_API_TOKEN") + if not token: + return None + config = Path.home() / ".config" / ".jira" / ".config.yml" + try: + text = config.read_text() + except OSError: + return None + server = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) + login = re.search(r"^login:\s*(\S+)", text, re.MULTILINE) + if not server or not login: + return None + base = server.group(1).rstrip("/") + if "://" not in base: + base = f"https://{base}" + if not base.startswith("https://"): + # The Basic auth header carries the API token; never send it in cleartext. + return None + auth = base64.b64encode(f"{login.group(1)}:{token}".encode()).decode() + return base, auth + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse redirects: urllib copies the Authorization header to the target.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp) + + +def open_changelog(request: urllib.request.Request): + """GET that never follows a redirect, so the token stays on the Jira host.""" + return urllib.request.build_opener(NoRedirect).open(request, timeout=15) + + +def changelog_dates( + key: str, account_id: str | None, api: tuple[str, str] | None +) -> tuple[date | None, date | None]: + """(last status change, date the current assignee took the issue). + + Both come from the same changelog payload, so the report pays one request per + issue. `statusCategoryChangedDate` is a fallback, not the truth: it ignores + moves inside a category, such as In Progress -> Review. + + Either value is None when the changelog has no such entry (the issue was + created in its current status or already assigned). A failed request raises + `ChangelogUnavailable` instead: "the API said no" and "the API did not + answer" must not collapse into the same value, because the caller falls back + to a different clock for the second one. + """ + if not api: + return None, None + server, auth = api + url = f"{server}/rest/api/3/issue/{key}?expand=changelog&fields=status,assignee" + request = urllib.request.Request( + url, headers={"Authorization": f"Basic {auth}", "Accept": "application/json"} + ) + try: + with open_changelog(request) as response: + payload = json.load(response) + except ( + urllib.error.URLError, + http.client.HTTPException, + OSError, + ValueError, + ) as exc: + # HTTPError is a URLError and JSONDecodeError/UnicodeDecodeError are + # ValueErrors: every transport or decode failure is one counted failure. + raise ChangelogUnavailable(f"{key}: {type(exc).__name__}") from exc + + changelog = payload.get("changelog") or {} + histories = changelog.get("histories") or [] + try: + total = int(changelog.get("total") or 0) + except (TypeError, ValueError): + total = 0 + if total > len(histories): + # The inline changelog is capped; a truncated read can miss the exact + # transition, so it must be counted instead of looking like "no entry". + raise ChangelogUnavailable( + f"{key}: changelog truncated ({len(histories)} of {total} entries)" + ) + + status_dates: list[date] = [] + assignment_dates: list[date] = [] + for entry in histories: + changed_status = changed_assignee = False + for change in entry.get("items") or []: + if change.get("field") == "status": + if status_change_counts(change): + changed_status = True + elif ( + account_id + and change.get("field") == "assignee" + and change.get("to") == account_id + ): + changed_assignee = True + if changed_status: + status_dates.append(parse_date(entry["created"])) + if changed_assignee: + assignment_dates.append(parse_date(entry["created"])) + + status_entered = max(status_dates) if status_dates else None + assigned = max(assignment_dates) if assignment_dates else None + return status_entered, assigned + + +def read_changelog( + key: str, account_id: str | None, api: tuple[str, str] | None +) -> tuple[tuple[date | None, date | None], str | None]: + """(dates, error). A failed read is counted, not read as "no entry". + + Collapsing both into (None, None) lets an expired token walk every item back + to the status category clock while the report still calls it the exact + signal, inflating the stale list and the "needs a decision" count. + """ + try: + return changelog_dates(key, account_id, api), None + except ChangelogUnavailable as exc: + return (None, None), str(exc) + + +def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: + """Reset the movement clock on an exact status change or a new owner. + + `statusCategoryChangedDate` only moves between To Do / In Progress / Done, so + an item that entered Review yesterday can still look stale by the category + date. The changelog has the exact transition. + + Assignment matters for the same reason blocked time does: time before the + current owner had the ticket is not the current owner's time. Both signals can + only lower the clock; neither can raise it. + """ + for item in items: + item["status_entered"] = None + item["assigned"] = None + item["days_since_assignment"] = None + + api = jira_api() + if not api: + return { + "available": False, + "failed": 0, + "checked": len(items), + "reason": "JIRA_API_TOKEN or jira-cli login not configured", + } + if not items: + return { + "available": True, + "failed": 0, + "checked": 0, + "status_dates": 0, + "assignments": 0, + } + + with ThreadPoolExecutor(max_workers=jobs) as pool: + results = list( + pool.map( + lambda item: read_changelog(item["key"], item.get("assignee_id"), api), + items, + ) + ) + + status_found = assignment_found = failed = 0 + for item, ((status_entered, assigned), error) in zip(items, results): + if error: + failed += 1 + if status_entered: + status_found += 1 + item["status_entered"] = status_entered.isoformat() + item["days_in_status"] = min( + item["days_in_status"], (today - status_entered).days + ) + if assigned: + assignment_found += 1 + item["assigned"] = assigned.isoformat() + item["days_since_assignment"] = (today - assigned).days + + signals = [item["days_in_status"]] + if item["days_since_comment"] is not None: + signals.append(item["days_since_comment"]) + if item["days_since_assignment"] is not None: + signals.append(item["days_since_assignment"]) + item["days_without_movement"] = min(signals) + + return { + "available": failed == 0, + "failed": failed, + "checked": len(items), + "status_dates": status_found, + "assignments": assignment_found, + } + + +PROJECT_KEY = re.compile(r"^[A-Z][A-Z0-9_]{1,9}$") + + +def project_key(value: str) -> str: + """A project key lands in JQL unquoted, so reject anything that is not one.""" + if not PROJECT_KEY.match(value): + raise argparse.ArgumentTypeError(f"not a Jira project key: {value!r}") + return value diff --git a/hyperfleet-jira/scripts/pulse_check.py b/hyperfleet-jira/scripts/pulse_check.py index bc92a25..7249fd8 100755 --- a/hyperfleet-jira/scripts/pulse_check.py +++ b/hyperfleet-jira/scripts/pulse_check.py @@ -28,94 +28,33 @@ from __future__ import annotations import argparse -import base64 -import http.client import json -import os -import re -import subprocess import sys -import urllib.error -import urllib.request -from concurrent.futures import ThreadPoolExecutor -from datetime import date, datetime, timezone -from pathlib import Path - - -class PulseError(Exception): - pass - - -class ChangelogUnavailable(Exception): - """A changelog read failed; it must not be read as "no entry".""" - - -# A move between these statuses is classification, not work. HYPERFLEET creates -# issues in `New`; a bulk New -> Backlog sweep must not reset the movement clock. -TRIVIAL_STATUSES = {"New", "Backlog"} - - -def status_change_counts(change: dict) -> bool: - """True when a status transition is workflow movement, not classification.""" - from_status = (change.get("fromString") or "").strip() - to_status = (change.get("toString") or "").strip() - return not (from_status in TRIVIAL_STATUSES and to_status in TRIVIAL_STATUSES) - - -def run_jira(args: list[str], binary: str) -> str: - try: - proc = subprocess.run( - [binary, *args], capture_output=True, text=True, timeout=120 - ) - except (subprocess.TimeoutExpired, FileNotFoundError) as exc: - raise PulseError(f"jira {' '.join(args[:2])} could not run: {exc}") from exc - if proc.returncode != 0: - raise PulseError( - f"jira {' '.join(args)} failed ({proc.returncode}): " - f"{(proc.stderr or proc.stdout).strip()[:300]}" - ) - return proc.stdout - - -def parse_date(value: str) -> date: - return datetime.strptime(value[:10], "%Y-%m-%d").date() - - -def jira_base_url() -> str | None: - """Read the server from the jira-cli config, so the report never hardcodes it. - - Bare keys are only resolvable if the reader knows the server; one line here - saves every table from carrying a link per row. - """ - config = Path.home() / ".config" / ".jira" / ".config.yml" - try: - text = config.read_text() - except OSError: - return None - match = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) - if not match: - return None - server = match.group(1).rstrip("/") - if "://" not in server: - server = f"https://{server}" - if not server.startswith("https://"): - return None - return f"{server}/browse/" - - -def ticket_ref(key: str, base_url: str | None, style: str) -> str: - """Render a ticket key for the destination. - - The same report is pasted into the TUI, Slack and log files, and only one of - the three understands `[text](url)`. Keep the syntax switchable instead of - guessing at render time. - """ - if not base_url or style == "bare": - return key - url = f"{base_url}{key}" - if style == "slack": - return f"<{url}|{key}>" - return f"[{key}]({url})" +from datetime import datetime, timezone + +# The Jira layer is shared with sprint_status.py: one definition of "work is Done +# by category", one pager, one changelog reader. See jira_common.py. +from jira_common import ( + OPEN_STATUS_JQL, + ChangelogUnavailable, + JiraError, + active_sprint, + apply_changelog_signals, + describe, + fetch_all, + jira_base_url, + open_links, + parse_date, + project_key, + run_jira, + status_category, + status_name, + ticket_ref, +) + +# One error type, two names: the caller sees the script it invoked, not the module +# that raised. The alias also keeps existing tests reading naturally. +PulseError = JiraError def prose(text: str) -> str: @@ -127,229 +66,10 @@ def cell(text: str) -> str: return prose(text).replace("|", "\\|") -def jira_api() -> tuple[str, str] | None: - """(server, basic-auth header) for Jira's REST API, or None. - - The changelog is the only place Jira records the exact status transition and - the owner change, and jira-cli exposes neither. The token is the same - `JIRA_API_TOKEN` the CLI uses; without it both signals are unavailable and the - scripts fall back to `statusCategoryChangedDate`. - """ - token = os.environ.get("JIRA_API_TOKEN") - if not token: - return None - config = Path.home() / ".config" / ".jira" / ".config.yml" - try: - text = config.read_text() - except OSError: - return None - server = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) - login = re.search(r"^login:\s*(\S+)", text, re.MULTILINE) - if not server or not login: - return None - base = server.group(1).rstrip("/") - if "://" not in base: - base = f"https://{base}" - if not base.startswith("https://"): - # The Basic auth header carries the API token; never send it in cleartext. - return None - auth = base64.b64encode(f"{login.group(1)}:{token}".encode()).decode() - return base, auth - - -class NoRedirect(urllib.request.HTTPRedirectHandler): - """Refuse redirects: urllib copies the Authorization header to the target.""" - - def redirect_request(self, req, fp, code, msg, headers, newurl): - raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp) - - -def open_changelog(request: urllib.request.Request): - """GET that never follows a redirect, so the token stays on the Jira host.""" - return urllib.request.build_opener(NoRedirect).open(request, timeout=15) - - -def changelog_dates( - key: str, account_id: str | None, api: tuple[str, str] | None -) -> tuple[date | None, date | None]: - """(last status change, date the current assignee took the issue). - - Both come from the same changelog payload, so the report pays one request per - issue. `statusCategoryChangedDate` is a fallback, not the truth: it ignores - moves inside a category, such as In Progress -> Review. - - Either value is None when the changelog has no such entry (the issue was - created in its current status or already assigned). A failed request raises - `ChangelogUnavailable` instead: "the API said no" and "the API did not - answer" must not collapse into the same value, because the caller falls back - to a different clock for the second one. - """ - if not api: - return None, None - server, auth = api - url = f"{server}/rest/api/3/issue/{key}?expand=changelog&fields=status,assignee" - request = urllib.request.Request( - url, headers={"Authorization": f"Basic {auth}", "Accept": "application/json"} - ) - try: - with open_changelog(request) as response: - payload = json.load(response) - except ( - urllib.error.URLError, - http.client.HTTPException, - OSError, - ValueError, - ) as exc: - # HTTPError is a URLError and JSONDecodeError/UnicodeDecodeError are - # ValueErrors: every transport or decode failure is one counted failure. - raise ChangelogUnavailable(f"{key}: {type(exc).__name__}") from exc - - changelog = payload.get("changelog") or {} - histories = changelog.get("histories") or [] - try: - total = int(changelog.get("total") or 0) - except (TypeError, ValueError): - total = 0 - if total > len(histories): - # The inline changelog is capped; a truncated read can miss the exact - # transition, so it must be counted instead of looking like "no entry". - raise ChangelogUnavailable( - f"{key}: changelog truncated ({len(histories)} of {total} entries)" - ) - - status_dates: list[date] = [] - assignment_dates: list[date] = [] - for entry in histories: - changed_status = changed_assignee = False - for change in entry.get("items") or []: - if change.get("field") == "status": - if status_change_counts(change): - changed_status = True - elif ( - account_id - and change.get("field") == "assignee" - and change.get("to") == account_id - ): - changed_assignee = True - if changed_status: - status_dates.append(parse_date(entry["created"])) - if changed_assignee: - assignment_dates.append(parse_date(entry["created"])) - - status_entered = max(status_dates) if status_dates else None - assigned = max(assignment_dates) if assignment_dates else None - return status_entered, assigned - - -def read_changelog( - key: str, account_id: str | None, api: tuple[str, str] | None -) -> tuple[tuple[date | None, date | None], str | None]: - """(dates, error). A failed read is counted, not read as "no entry". - - Collapsing both into (None, None) lets an expired token walk every item back - to the status category clock while the report still calls it the exact - signal, and the 20-day rung then fires on items that moved last week. - """ - try: - return changelog_dates(key, account_id, api), None - except ChangelogUnavailable as exc: - return (None, None), str(exc) - - -def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: - """Reset the movement clock on an exact status change or a new owner. - - `statusCategoryChangedDate` only moves between To Do / In Progress / Done, so - an item that entered Review yesterday can still look stale by the category - date. The changelog has the exact transition. - - Assignment matters for the same reason blocked time does: time before the - current owner had the ticket is not the current owner's time. Both signals can - only lower the clock; neither can raise it. - """ - for item in items: - item["status_entered"] = None - item["assigned"] = None - item["days_since_assignment"] = None - - api = jira_api() - if not api: - return { - "available": False, - "failed": 0, - "checked": len(items), - "reason": "JIRA_API_TOKEN or jira-cli login not configured", - } - if not items: - return { - "available": True, - "failed": 0, - "checked": 0, - "status_dates": 0, - "assignments": 0, - } - - with ThreadPoolExecutor(max_workers=jobs) as pool: - results = list( - pool.map( - lambda item: read_changelog(item["key"], item.get("assignee_id"), api), - items, - ) - ) - - status_found = assignment_found = failed = 0 - for item, ((status_entered, assigned), error) in zip(items, results): - if error: - failed += 1 - if status_entered: - status_found += 1 - item["status_entered"] = status_entered.isoformat() - item["days_in_status"] = min( - item["days_in_status"], (today - status_entered).days - ) - if assigned: - assignment_found += 1 - item["assigned"] = assigned.isoformat() - item["days_since_assignment"] = (today - assigned).days - - signals = [item["days_in_status"]] - if item["days_since_comment"] is not None: - signals.append(item["days_since_comment"]) - if item["days_since_assignment"] is not None: - signals.append(item["days_since_assignment"]) - item["days_without_movement"] = min(signals) - - return { - "available": failed == 0, - "failed": failed, - "checked": len(items), - "status_dates": status_found, - "assignments": assignment_found, - } - - -def active_sprint(project: str, binary: str) -> dict: - out = run_jira( - [ - "sprint", "list", "-p", project, "--state", "active", - "--plain", "--no-truncate", - "--columns", "ID,NAME,START,END,STATE", - ], - binary, - ) - rows = [line.split("\t") for line in out.strip().splitlines()] - if len(rows) < 2: - raise PulseError(f"no active sprint found for project {project}") - if len(rows) > 2: - print(f"warning: {len(rows) - 1} active sprints; using {rows[1][1]}", file=sys.stderr) - sid, name, start, end, state = (rows[1] + [""] * 5)[:5] - return {"id": sid, "name": name, "start": start[:10], "end": end[:10], "state": state} - - def large_item_keys(project: str, min_sp: int, sp_field_name: str, binary: str) -> list[str]: jql = ( f'project = {project} AND sprint in openSprints() ' - f'AND "{sp_field_name}" >= {min_sp} AND status != Closed' + f'AND "{sp_field_name}" >= {min_sp} AND {OPEN_STATUS_JQL}' ) out = run_jira( ["issue", "list", "-q", jql, "-p", project, "--plain", "--no-headers", "--columns", "KEY"], @@ -358,80 +78,6 @@ def large_item_keys(project: str, min_sp: int, sp_field_name: str, binary: str) return [line.strip() for line in out.splitlines() if line.strip()] -def fetch_issue(key: str, project: str, binary: str) -> dict: - try: - return json.loads(run_jira(["issue", "view", key, "-p", project, "--raw"], binary)) - except (PulseError, json.JSONDecodeError) as exc: - raise PulseError(f"could not read {key}: {exc}") from exc - - -def fetch_all(keys: list[str], project: str, binary: str, jobs: int) -> dict[str, dict]: - unique = sorted(set(keys)) - with ThreadPoolExecutor(max_workers=jobs) as pool: - docs = list(pool.map(lambda k: fetch_issue(k, project, binary), unique)) - return {doc["key"]: doc for doc in docs} - - -def link_targets(doc: dict) -> tuple[list[str], list[str]]: - """Return (blocked_by, blocks) keys from the issue links. - - Orientation matters: Jira labels every Blocks link with inward="is blocked by" - and outward="blocks", so the type label alone cannot tell you the direction. - What decides is which side of the link carries the other issue. - """ - blocked_by, blocks = [], [] - for link in doc["fields"].get("issuelinks") or []: - kind = link.get("type") or {} - inward, outward = link.get("inwardIssue"), link.get("outwardIssue") - if inward and inward.get("key") and (kind.get("inward") or "").strip().lower() == "is blocked by": - blocked_by.append(inward["key"]) - elif outward and outward.get("key") and (kind.get("outward") or "").strip().lower() == "blocks": - blocks.append(outward["key"]) - return blocked_by, blocks - - -def human_comment_dates(doc: dict) -> list[date]: - dates = [] - for comment in (doc["fields"].get("comment") or {}).get("comments") or []: - author = comment.get("author") or {} - if author.get("accountType") == "app": - continue - created = comment.get("created") - if created: - dates.append(parse_date(created)) - return dates - - -def describe(key: str, doc: dict, sp_field: str, today: date) -> dict: - fields = doc["fields"] - status_changed = parse_date(fields["statuscategorychangedate"]) - comments = human_comment_dates(doc) - last_comment = max(comments) if comments else None - days_in_status = (today - status_changed).days - days_since_comment = (today - last_comment).days if last_comment else None - signals = [days_in_status] + ([days_since_comment] if days_since_comment is not None else []) - blocked_by, blocks = link_targets(doc) - return { - "key": key, - "summary": fields.get("summary", ""), - "type": (fields.get("issuetype") or {}).get("name", ""), - "sp": fields.get(sp_field) or 0, - "owner": ((fields.get("assignee") or {}).get("displayName") or "").strip(), - "assignee_id": (fields.get("assignee") or {}).get("accountId") or None, - "status": (fields.get("status") or {}).get("name", ""), - "priority": (fields.get("priority") or {}).get("name", ""), - "epic": (fields.get("parent") or {}).get("key"), - "labels": fields.get("labels") or [], - "created": (fields.get("created") or "")[:10], - "days_without_movement": min(signals), - "days_in_status": days_in_status, - "days_since_comment": days_since_comment, - "last_comment": last_comment.isoformat() if last_comment else None, - "blocked_by": blocked_by, - "blocks": blocks, - } - - def assignment_is_binding(item: dict) -> bool: """True when the assignment date is what keeps the clock short. @@ -508,13 +154,19 @@ def build(args) -> dict: keys = large_item_keys(args.project, args.min_sp, args.sp_field_name, args.jira) docs = fetch_all(keys, args.project, args.jira, args.jobs) - items = [describe(k, d, args.sp_field, today) for k, d in docs.items()] + items = [] + for key, doc in docs.items(): + item = describe(key, doc, args.sp_field, today) + # The report sums points, so "no estimate" is zero here; describe keeps + # None so the sprint report can tell the two apart. + item["sp"] = item["sp"] or 0 + items.append(item) # Resolve the status of every link target so "blocked" and "blocks" mean open work only. targets = {k for item in items for k in item["blocked_by"] + item["blocks"]} - set(docs) extra = fetch_all(sorted(targets), args.project, args.jira, args.jobs) if targets else {} - status_of = {k: (d["fields"].get("status") or {}).get("name", "") for k, d in docs.items()} - status_of.update({k: (d["fields"].get("status") or {}).get("name", "") for k, d in extra.items()}) + status_of = {k: status_name(d) for k, d in {**docs, **extra}.items()} + category_of = {k: status_category(d) for k, d in {**docs, **extra}.items()} owner_of = { k: (((d["fields"].get("assignee") or {}).get("displayName")) or "").strip() for k, d in {**docs, **extra}.items() @@ -535,7 +187,7 @@ def build(args) -> dict: ) for item in items: - item["open_blockers"] = [k for k in item["blocked_by"] if status_of.get(k) != "Closed"] + item["open_blockers"] = open_links(item["blocked_by"], category_of) item["blocked"] = bool(item["open_blockers"]) item["blocker_detail"] = [ { @@ -546,7 +198,7 @@ def build(args) -> dict: } for k in item["open_blockers"] ] - item["blocks_open"] = [k for k in item["blocks"] if status_of.get(k) != "Closed"] + item["blocks_open"] = open_links(item["blocks"], category_of) item["ask"] = suggested_ask(item) owned = [i for i in items if i["owner"]] @@ -709,16 +361,6 @@ def render_text(data: dict) -> str: return "\n".join(lines) -PROJECT_KEY = re.compile(r"^[A-Z][A-Z0-9_]{1,9}$") - - -def project_key(value: str) -> str: - """A project key lands in JQL unquoted, so reject anything that is not one.""" - if not PROJECT_KEY.match(value): - raise argparse.ArgumentTypeError(f"not a Jira project key: {value!r}") - return value - - def field_name(value: str) -> str: """A field name sits inside quotes in JQL; keep quotes and escapes out.""" if '"' in value or "\\" in value: diff --git a/hyperfleet-jira/scripts/sprint_status.py b/hyperfleet-jira/scripts/sprint_status.py index 25c480b..c53968c 100755 --- a/hyperfleet-jira/scripts/sprint_status.py +++ b/hyperfleet-jira/scripts/sprint_status.py @@ -34,147 +34,35 @@ from __future__ import annotations import argparse -import base64 -import http.client import json -import os -import re -import subprocess import sys -import urllib.error -import urllib.request -from concurrent.futures import ThreadPoolExecutor from datetime import date, datetime, timezone -from pathlib import Path - -class SprintError(Exception): - pass - - -class ChangelogUnavailable(Exception): - """A changelog read failed; it must not be read as "no entry".""" - - -CATEGORY_ORDER = {"To Do": 0, "In Progress": 1, "Done": 2} - -# A move between these statuses is classification, not work. HYPERFLEET creates -# issues in `New`; a bulk New -> Backlog sweep must not reset the movement clock. -TRIVIAL_STATUSES = {"New", "Backlog"} - - -def status_change_counts(change: dict) -> bool: - """True when a status transition is workflow movement, not classification.""" - from_status = (change.get("fromString") or "").strip() - to_status = (change.get("toString") or "").strip() - return not (from_status in TRIVIAL_STATUSES and to_status in TRIVIAL_STATUSES) - - -# -------------------------------------------------------------------------- -# jira-cli plumbing -# -------------------------------------------------------------------------- - - -def run_jira(args: list[str], binary: str) -> str: - try: - proc = subprocess.run( - [binary, *args], capture_output=True, text=True, timeout=120 - ) - except (subprocess.TimeoutExpired, FileNotFoundError) as exc: - raise SprintError(f"jira {' '.join(args[:2])} could not run: {exc}") from exc - if proc.returncode != 0: - raise SprintError( - f"jira {' '.join(args)} failed ({proc.returncode}): " - f"{(proc.stderr or proc.stdout).strip()[:300]}" - ) - return proc.stdout - - -def parse_date(value: str) -> date: - return datetime.strptime(value[:10], "%Y-%m-%d").date() - - -def key_number(key: str) -> int: - _, _, number = key.rpartition("-") - return int(number) - - -def jql_project(project: str) -> str: - return f"project = {project}" - - -def search_keys(jql: str, project: str, binary: str, limit: int = 100) -> list[str]: - """List every key matching `jql`, past the 100-issue page cap. - - `jira issue list --paginate :` ignores ``: every page - returns the same first N issues. It also rejects a limit above 100. So the - only way to walk a larger result is to move the search window with JQL - itself, using the lowest key of each batch as the next boundary. - - Returns the keys in the order the CLI emitted them, plus a `truncated` flag - is not needed: an incomplete result raises instead of lying. - """ - keys: list[str] = [] - seen: set[str] = set() - boundary: str | None = None - - for _ in range(200): - query = jql if boundary is None else f"({jql}) AND key < {boundary}" - out = run_jira( - [ - "issue", "list", "-q", query, "-p", project, - "--plain", "--no-headers", "--columns", "KEY", - "--order-by", "key", "--paginate", f"0:{limit}", - ], - binary, - ) - batch = [line.strip() for line in out.splitlines() if line.strip()] - fresh = [key for key in batch if key not in seen] - if not fresh: - return keys - keys.extend(fresh) - seen.update(fresh) - if len(batch) < limit: - return keys - boundary = min(batch, key=key_number) - - raise SprintError( - f"gave up paging after 200 batches ({len(keys)} keys); narrow the JQL" - ) - - -def sprint_rows(project: str, state: str, binary: str) -> list[dict]: - out = run_jira( - [ - "sprint", "list", "-p", project, "--state", state, - "--plain", "--no-truncate", - "--columns", "ID,NAME,START,END,STATE", - ], - binary, - ) - lines = [line for line in out.strip().splitlines() if line.strip()] - rows = [] - for line in lines[1:]: - sid, name, start, end, sprint_state = (line.split("\t") + [""] * 5)[:5] - rows.append( - { - "id": sid.strip(), - "name": name.strip(), - "start": start.strip()[:10], - "end": end.strip()[:10], - "state": sprint_state.strip(), - } - ) - return rows - - -def active_sprint(project: str, binary: str) -> dict: - rows = sprint_rows(project, "active", binary) - if not rows: - raise SprintError(f"no active sprint found for project {project}") - if len(rows) > 1: - print(f"warning: {len(rows)} active sprints; using {rows[0]['name']}", file=sys.stderr) - return rows[0] +# The Jira layer is shared with pulse_check.py: one definition of "work is Done by +# category", one pager, one changelog reader. See jira_common.py. +from jira_common import ( + CATEGORY_ORDER, + ChangelogUnavailable, + JiraError, + active_sprint, + apply_changelog_signals, + describe, + fetch_all, + jira_base_url, + jql_project, + open_links, + parse_date, + project_key, + search_keys, + sprint_rows, + status_category, + status_name, + ticket_ref, +) + +# One error type, two names: the caller sees the script it invoked, not the module +# that raised. The alias also keeps existing tests reading naturally. +SprintError = JiraError def previous_sprint( @@ -194,71 +82,6 @@ def previous_sprint( return max(rows, key=lambda row: row["end"]) -def fetch_issue(key: str, project: str, binary: str) -> dict: - try: - return json.loads( - run_jira(["issue", "view", key, "-p", project, "--raw"], binary) - ) - except (SprintError, json.JSONDecodeError) as exc: - raise SprintError(f"could not read {key}: {exc}") from exc - - -def fetch_all(keys: list[str], project: str, binary: str, jobs: int) -> dict[str, dict]: - unique = sorted(set(keys), key=key_number) - with ThreadPoolExecutor(max_workers=jobs) as pool: - docs = list(pool.map(lambda key: fetch_issue(key, project, binary), unique)) - return {doc["key"]: doc for doc in docs} - - -# -------------------------------------------------------------------------- -# Issue shape -# -------------------------------------------------------------------------- - - -def link_targets(doc: dict) -> tuple[list[str], list[str]]: - """Return (blocked_by, blocks) keys from the issue links. - - Jira labels every Blocks link with inward="is blocked by" and - outward="blocks", so the type label alone cannot tell you the direction. - What decides is which side of the link carries the other issue. - """ - blocked_by, blocks = [], [] - for link in doc["fields"].get("issuelinks") or []: - kind = link.get("type") or {} - inward, outward = link.get("inwardIssue"), link.get("outwardIssue") - if ( - inward - and inward.get("key") - and (kind.get("inward") or "").strip().lower() == "is blocked by" - ): - blocked_by.append(inward["key"]) - elif ( - outward - and outward.get("key") - and (kind.get("outward") or "").strip().lower() == "blocks" - ): - blocks.append(outward["key"]) - return blocked_by, blocks - - -def human_comment_dates(doc: dict) -> list[date]: - """Comment dates written by people, not integrations. - - Jira automation comments (`author.accountType == "app"`) are not movement: - a ticket whose only recent comment came from "Automation for Jira" was not - touched by anyone. - """ - dates = [] - for comment in (doc["fields"].get("comment") or {}).get("comments") or []: - author = comment.get("author") or {} - if author.get("accountType") == "app": - continue - created = comment.get("created") - if created: - dates.append(parse_date(created)) - return dates - - def sprint_of(doc: dict, sprint_id: str) -> dict | None: for sprint in doc["fields"].get("customfield_10020") or []: if str(sprint.get("id")) == str(sprint_id): @@ -266,41 +89,6 @@ def sprint_of(doc: dict, sprint_id: str) -> dict | None: return None -def describe(doc: dict, sp_field: str, today: date) -> dict: - fields = doc["fields"] - status = fields.get("status") or {} - category = (status.get("statusCategory") or {}).get("name", "") - status_changed = parse_date(fields["statuscategorychangedate"]) - comments = human_comment_dates(doc) - last_comment = max(comments) if comments else None - signals = [(today - status_changed).days] - if last_comment: - signals.append((today - last_comment).days) - blocked_by, blocks = link_targets(doc) - points = fields.get(sp_field) - - return { - "key": doc["key"], - "summary": (fields.get("summary") or "").strip(), - "type": (fields.get("issuetype") or {}).get("name", ""), - "sp": points if isinstance(points, (int, float)) else None, - "owner": ((fields.get("assignee") or {}).get("displayName") or "").strip(), - "assignee_id": (fields.get("assignee") or {}).get("accountId") or None, - "status": status.get("name", ""), - "category": category, - "priority": (fields.get("priority") or {}).get("name", ""), - "epic": (fields.get("parent") or {}).get("key"), - "created": (fields.get("created") or "")[:10], - "days_in_status": (today - status_changed).days, - "days_since_comment": (today - last_comment).days if last_comment else None, - "days_without_movement": min(signals), - "last_comment": last_comment.isoformat() if last_comment else None, - "blocked_by": blocked_by, - "blocks": blocks, - "is_done": category == "Done", - } - - def resolve_blockers( items: list[dict], docs: dict[str, dict], project: str, binary: str, jobs: int ) -> None: @@ -315,25 +103,20 @@ def resolve_blockers( status_of = { key: { - "status": (doc["fields"].get("status") or {}).get("name", ""), - "category": ( - ((doc["fields"].get("status") or {}).get("statusCategory") or {}).get("name", "") - ), + "status": status_name(doc), + "category": status_category(doc), "owner": ((doc["fields"].get("assignee") or {}).get("displayName") or "").strip(), } for key, doc in {**docs, **extra}.items() } + category_of = {key: detail["category"] for key, detail in status_of.items()} for item in items: item["blocker_detail"] = [ {"key": key, **status_of.get(key, {"status": "?", "category": "?", "owner": ""})} for key in item["blocked_by"] ] - item["open_blockers"] = [ - detail["key"] - for detail in item["blocker_detail"] - if detail["category"] != "Done" - ] + item["open_blockers"] = open_links(item["blocked_by"], category_of) item["blocked"] = bool(item["open_blockers"]) @@ -513,12 +296,17 @@ def capacity( def baseline_for( sprint: dict | None, project: str, sp_field: str, binary: str, jobs: int, today: date ) -> dict | None: - """Previous sprint totals. + """Previous sprint totals, measured at the baseline sprint's end. `committed` is the SP currently sitting in that sprint, not the SP committed on day one: Jira keeps no record of scope added or removed mid-sprint, so the number is an upper bound. The report says so instead of implying precision it does not have. + + `delivered` only counts work that was already Done when the baseline sprint + ended. Measuring at `today` credits points closed during the current sprint to + a sprint that was already over, which inflates the baseline and every + projection built on it. """ if not sprint: return None @@ -527,9 +315,14 @@ def baseline_for( if not keys: return None docs = fetch_all(keys, project, binary, jobs) - items = [describe(doc, sp_field, today) for doc in docs.values()] + items = [describe(doc["key"], doc, sp_field, today) for doc in docs.values()] committed = sum(item["sp"] or 0 for item in items) - delivered = sum(item["sp"] or 0 for item in items if item["is_done"]) + end = parse_date(sprint["end"]) if sprint.get("end") else None + delivered = sum( + item["sp"] or 0 + for item in items + if item["is_done"] and _closed_by(item["status_changed"], end) + ) try: days = (parse_date(sprint["end"]) - parse_date(sprint["start"])).days + 1 except (KeyError, ValueError): @@ -537,6 +330,7 @@ def baseline_for( return { "sprint": sprint["name"], "id": sprint["id"], + "end": sprint.get("end"), "items": len(items), "committed_sp": committed, "delivered_sp": delivered, @@ -545,238 +339,20 @@ def baseline_for( } -def jira_base_url() -> str | None: - """Read the server from the jira-cli config, so the report never hardcodes it.""" - config = Path.home() / ".config" / ".jira" / ".config.yml" - try: - text = config.read_text() - except OSError: - return None - match = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) - if not match: - return None - server = match.group(1).rstrip("/") - if "://" not in server: - server = f"https://{server}" - if not server.startswith("https://"): - return None - return f"{server}/browse/" - - -def ticket_ref(key: str, base_url: str | None, style: str) -> str: - """Render a ticket key for the destination. - - The same report is pasted into the TUI, Slack and log files, and only one of - the three understands `[text](url)`. Keep the syntax switchable instead of - guessing at render time. - """ - if not base_url or style == "bare": - return key - url = f"{base_url}{key}" - if style == "slack": - return f"<{url}|{key}>" - return f"[{key}]({url})" - - -def jira_api() -> tuple[str, str] | None: - """(server, basic-auth header) for Jira's REST API, or None. - - The changelog is the only place Jira records the exact status transition and - the owner change, and jira-cli exposes neither. The token is the same - `JIRA_API_TOKEN` the CLI uses; without it both signals are unavailable and the - report falls back to `statusCategoryChangedDate`. - """ - token = os.environ.get("JIRA_API_TOKEN") - if not token: - return None - config = Path.home() / ".config" / ".jira" / ".config.yml" - try: - text = config.read_text() - except OSError: - return None - server = re.search(r"^server:\s*(\S+)", text, re.MULTILINE) - login = re.search(r"^login:\s*(\S+)", text, re.MULTILINE) - if not server or not login: - return None - base = server.group(1).rstrip("/") - if "://" not in base: - base = f"https://{base}" - if not base.startswith("https://"): - # The Basic auth header carries the API token; never send it in cleartext. - return None - auth = base64.b64encode(f"{login.group(1)}:{token}".encode()).decode() - return base, auth - - -class NoRedirect(urllib.request.HTTPRedirectHandler): - """Refuse redirects: urllib copies the Authorization header to the target.""" - - def redirect_request(self, req, fp, code, msg, headers, newurl): - raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp) - - -def open_changelog(request: urllib.request.Request): - """GET that never follows a redirect, so the token stays on the Jira host.""" - return urllib.request.build_opener(NoRedirect).open(request, timeout=15) - - -def changelog_dates( - key: str, account_id: str | None, api: tuple[str, str] | None -) -> tuple[date | None, date | None]: - """(last status change, date the current assignee took the issue). - - Both come from the same changelog payload, so the report pays one request per - issue. `statusCategoryChangedDate` is a fallback, not the truth: it ignores - moves inside a category, such as In Progress -> Review. +def _closed_by(status_changed: str | None, end: date | None) -> bool: + """True when the item entered Done on or before `end`. - Either value is None when the changelog has no such entry (the issue was - created in its current status or already assigned). A failed request raises - `ChangelogUnavailable` instead: "the API said no" and "the API did not - answer" must not collapse into the same value, because the caller falls back - to a different clock for the second one. - """ - if not api: - return None, None - server, auth = api - url = f"{server}/rest/api/3/issue/{key}?expand=changelog&fields=status,assignee" - request = urllib.request.Request( - url, headers={"Authorization": f"Basic {auth}", "Accept": "application/json"} - ) - try: - with open_changelog(request) as response: - payload = json.load(response) - except ( - urllib.error.URLError, - http.client.HTTPException, - OSError, - ValueError, - ) as exc: - # HTTPError is a URLError and JSONDecodeError/UnicodeDecodeError are - # ValueErrors: every transport or decode failure is one counted failure. - raise ChangelogUnavailable(f"{key}: {type(exc).__name__}") from exc - - changelog = payload.get("changelog") or {} - histories = changelog.get("histories") or [] - try: - total = int(changelog.get("total") or 0) - except (TypeError, ValueError): - total = 0 - if total > len(histories): - # The inline changelog is capped; a truncated read can miss the exact - # transition, so it must be counted instead of looking like "no entry". - raise ChangelogUnavailable( - f"{key}: changelog truncated ({len(histories)} of {total} entries)" - ) - - status_dates: list[date] = [] - assignment_dates: list[date] = [] - for entry in histories: - changed_status = changed_assignee = False - for change in entry.get("items") or []: - if change.get("field") == "status": - if status_change_counts(change): - changed_status = True - elif ( - account_id - and change.get("field") == "assignee" - and change.get("to") == account_id - ): - changed_assignee = True - if changed_status: - status_dates.append(parse_date(entry["created"])) - if changed_assignee: - assignment_dates.append(parse_date(entry["created"])) - - status_entered = max(status_dates) if status_dates else None - assigned = max(assignment_dates) if assignment_dates else None - return status_entered, assigned - - -def read_changelog( - key: str, account_id: str | None, api: tuple[str, str] | None -) -> tuple[tuple[date | None, date | None], str | None]: - """(dates, error). A failed read is counted, not read as "no entry". - - Collapsing both into (None, None) lets an expired token walk every item back - to the status category clock while the report still calls it the exact - signal, inflating the stale list and the "needs a decision" count. + Without a readable sprint end there is nothing to compare against, so the item + counts: an unparsed date must not silently report zero delivery. """ + if end is None: + return True + if not status_changed: + return False try: - return changelog_dates(key, account_id, api), None - except ChangelogUnavailable as exc: - return (None, None), str(exc) - - -def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: - """Reset the movement clock on an exact status change or a new owner. - - `statusCategoryChangedDate` only moves between To Do / In Progress / Done, so - an item that entered Review yesterday can still look stale by the category - date. The changelog has the exact transition. - - Assignment matters for the same reason blocked time does: time before the - current owner had the ticket is not the current owner's time. Both signals can - only lower the clock; neither can raise it. - """ - for item in items: - item["status_entered"] = None - item["assigned"] = None - item["days_since_assignment"] = None - - api = jira_api() - if not api: - return { - "available": False, - "failed": 0, - "checked": len(items), - "reason": "JIRA_API_TOKEN or jira-cli login not configured", - } - if not items: - return { - "available": True, - "failed": 0, - "checked": 0, - "status_dates": 0, - "assignments": 0, - } - - with ThreadPoolExecutor(max_workers=jobs) as pool: - results = list( - pool.map( - lambda item: read_changelog(item["key"], item.get("assignee_id"), api), - items, - ) - ) - - status_found = assignment_found = failed = 0 - for item, ((status_entered, assigned), error) in zip(items, results): - if error: - failed += 1 - if status_entered: - status_found += 1 - item["status_entered"] = status_entered.isoformat() - item["days_in_status"] = min( - item["days_in_status"], (today - status_entered).days - ) - if assigned: - assignment_found += 1 - item["assigned"] = assigned.isoformat() - item["days_since_assignment"] = (today - assigned).days - - signals = [item["days_in_status"]] - if item["days_since_comment"] is not None: - signals.append(item["days_since_comment"]) - if item["days_since_assignment"] is not None: - signals.append(item["days_since_assignment"]) - item["days_without_movement"] = min(signals) - - return { - "available": failed == 0, - "failed": failed, - "checked": len(items), - "status_dates": status_found, - "assignments": assignment_found, - } + return parse_date(status_changed) <= end + except ValueError: + return False # -------------------------------------------------------------------------- @@ -800,7 +376,7 @@ def build(args) -> dict: jql = f'{jql_project(args.project)} AND sprint = {sprint["id"]}' keys = search_keys(jql, args.project, args.jira) docs = fetch_all(keys, args.project, args.jira, args.jobs) - items = [describe(doc, args.sp_field, today) for doc in docs.values()] + items = [describe(doc["key"], doc, args.sp_field, today) for doc in docs.values()] goal = None for doc in docs.values(): @@ -924,7 +500,9 @@ def build(args) -> dict: ), "baseline_basis": ( "committed_sp counts the story points currently in the previous sprint, " - "not the scope committed on day one; Jira does not keep that history" + "not the scope committed on day one; Jira does not keep that history. " + "delivered_sp counts only work Done by the previous sprint's end date, " + "so work closed later is not credited to it" ), }, } @@ -962,9 +540,10 @@ def ref(key: str) -> str: baseline = data.get("baseline") if baseline: + cutoff = f" by {baseline['end']}" if baseline.get("end") else "" lines.append( f"Previous sprint baseline: {baseline['committed_sp']:g} SP committed / " - f"{baseline['delivered_sp']:g} SP delivered ({baseline['percent']:g}%) " + f"{baseline['delivered_sp']:g} SP delivered{cutoff} ({baseline['percent']:g}%) " f"across {baseline['items']} items ({baseline['sprint']})" ) else: @@ -1113,16 +692,6 @@ def ref(key: str) -> str: return "\n".join(lines) -PROJECT_KEY = re.compile(r"^[A-Z][A-Z0-9_]{1,9}$") - - -def project_key(value: str) -> str: - """A project key lands in JQL unquoted, so reject anything that is not one.""" - if not PROJECT_KEY.match(value): - raise argparse.ArgumentTypeError(f"not a Jira project key: {value!r}") - return value - - def main() -> int: parser = argparse.ArgumentParser(description="Collect the sprint status data.") parser.add_argument("--project", default="HYPERFLEET", type=project_key) diff --git a/hyperfleet-jira/tests/test_pulse_check.py b/hyperfleet-jira/tests/test_pulse_check.py index 8e863ab..fc03fd9 100644 --- a/hyperfleet-jira/tests/test_pulse_check.py +++ b/hyperfleet-jira/tests/test_pulse_check.py @@ -20,6 +20,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +import jira_common as jc # noqa: E402 import pulse_check as pc # noqa: E402 TODAY = date(2026, 11, 3) @@ -75,17 +76,17 @@ def blocked_by_link(target): class LinkOrientationTest(unittest.TestCase): def test_outward_link_is_not_a_blocker(self): - blocked_by, blocks = pc.link_targets(doc(links=[blocks_link("HYPERFLEET-200")])) + blocked_by, blocks = jc.link_targets(doc(links=[blocks_link("HYPERFLEET-200")])) self.assertEqual(blocked_by, []) self.assertEqual(blocks, ["HYPERFLEET-200"]) def test_inward_link_is_a_blocker(self): - blocked_by, blocks = pc.link_targets(doc(links=[blocked_by_link("HYPERFLEET-200")])) + blocked_by, blocks = jc.link_targets(doc(links=[blocked_by_link("HYPERFLEET-200")])) self.assertEqual(blocked_by, ["HYPERFLEET-200"]) self.assertEqual(blocks, []) def test_both_directions_in_one_issue(self): - blocked_by, blocks = pc.link_targets( + blocked_by, blocks = jc.link_targets( doc(links=[blocked_by_link("HYPERFLEET-200"), blocks_link("HYPERFLEET-201")]) ) self.assertEqual(blocked_by, ["HYPERFLEET-200"]) @@ -94,13 +95,13 @@ def test_both_directions_in_one_issue(self): class MovementTest(unittest.TestCase): def test_app_comments_are_not_movement(self): - dates = pc.human_comment_dates( + dates = jc.human_comment_dates( doc(comments=[comment("2026-11-02", "Automation for Jira", "app")]) ) self.assertEqual(dates, []) def test_human_comment_is_movement(self): - dates = pc.human_comment_dates(doc(comments=[comment("2026-11-02")])) + dates = jc.human_comment_dates(doc(comments=[comment("2026-11-02")])) self.assertEqual(dates, [date(2026, 11, 2)]) def test_movement_uses_the_most_recent_signal(self): @@ -150,15 +151,15 @@ def item(self, **overrides): return base def apply(self, status_entered=None, assigned=None): - with mock.patch.object(pc, "jira_api", return_value=self.api), \ - mock.patch.object(pc, "changelog_dates", return_value=(status_entered, assigned)): + with mock.patch.object(jc, "jira_api", return_value=self.api), \ + mock.patch.object(jc, "changelog_dates", return_value=(status_entered, assigned)): return pc.apply_changelog_signals([self.item], TODAY, 1) def test_status_change_inside_a_category_resets_the_clock(self): item = self.item(days_in_status=15, days_without_movement=15) - with mock.patch.object(pc, "jira_api", return_value=self.api), \ + with mock.patch.object(jc, "jira_api", return_value=self.api), \ mock.patch.object( - pc, "changelog_dates", return_value=(date(2026, 10, 30), None) + jc, "changelog_dates", return_value=(date(2026, 10, 30), None) ): report = pc.apply_changelog_signals([item], TODAY, 1) self.assertEqual(item["days_in_status"], 4) @@ -177,9 +178,9 @@ def test_status_change_inside_a_category_resets_the_clock(self): def test_assignment_resets_the_clock(self): item = self.item() - with mock.patch.object(pc, "jira_api", return_value=self.api), \ + with mock.patch.object(jc, "jira_api", return_value=self.api), \ mock.patch.object( - pc, "changelog_dates", return_value=(None, date(2026, 10, 30)) + jc, "changelog_dates", return_value=(None, date(2026, 10, 30)) ): report = pc.apply_changelog_signals([item], TODAY, 1) self.assertEqual(item["days_without_movement"], 4) @@ -189,16 +190,16 @@ def test_assignment_resets_the_clock(self): def test_signals_never_raise_the_clock(self): item = self.item(days_in_status=2, days_since_comment=None, days_without_movement=2) - with mock.patch.object(pc, "jira_api", return_value=self.api), \ + with mock.patch.object(jc, "jira_api", return_value=self.api), \ mock.patch.object( - pc, "changelog_dates", return_value=(date(2026, 1, 1), date(2026, 1, 1)) + jc, "changelog_dates", return_value=(date(2026, 1, 1), date(2026, 1, 1)) ): pc.apply_changelog_signals([item], TODAY, 1) self.assertEqual(item["days_without_movement"], 2) def test_missing_token_keeps_the_old_clock(self): item = self.item() - with mock.patch.object(pc, "jira_api", return_value=None): + with mock.patch.object(jc, "jira_api", return_value=None): report = pc.apply_changelog_signals([item], TODAY, 1) self.assertFalse(report["available"]) self.assertEqual(item["days_without_movement"], 13) @@ -228,10 +229,10 @@ def histories(self): def test_changelog_returns_the_latest_status_and_assignment(self): with mock.patch.object( - pc, "open_changelog", return_value=self.Response(self.histories()) + jc, "open_changelog", return_value=self.Response(self.histories()) ): self.assertEqual( - pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), + jc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (date(2026, 10, 31), date(2026, 10, 31)), ) @@ -245,19 +246,19 @@ def test_new_to_backlog_is_classification_not_movement(self): } } with mock.patch.object( - pc, "open_changelog", return_value=self.Response(payload) + jc, "open_changelog", return_value=self.Response(payload) ): self.assertEqual( - pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (None, None) + jc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (None, None) ) def test_created_in_status_has_no_transition_date(self): payload = {"changelog": {"histories": []}} with mock.patch.object( - pc, "open_changelog", return_value=self.Response(payload) + jc, "open_changelog", return_value=self.Response(payload) ): self.assertEqual( - pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (None, None) + jc.changelog_dates("HYPERFLEET-1", "acc-1", self.api), (None, None) ) def test_binding_only_when_assignment_is_strictly_shortest(self): @@ -290,9 +291,9 @@ def item(self): } def test_a_failed_read_is_counted_not_hidden(self): - with mock.patch.object(pc, "jira_api", return_value=self.api), \ + with mock.patch.object(jc, "jira_api", return_value=self.api), \ mock.patch.object( - pc, "changelog_dates", + jc, "changelog_dates", side_effect=pc.ChangelogUnavailable("HYPERFLEET-1671: HTTPError"), ): report = pc.apply_changelog_signals([self.item()], TODAY, 1) @@ -302,9 +303,9 @@ def test_a_failed_read_is_counted_not_hidden(self): def test_a_failed_read_leaves_the_clock_alone(self): item = self.item() - with mock.patch.object(pc, "jira_api", return_value=self.api), \ + with mock.patch.object(jc, "jira_api", return_value=self.api), \ mock.patch.object( - pc, "changelog_dates", side_effect=pc.ChangelogUnavailable("boom") + jc, "changelog_dates", side_effect=pc.ChangelogUnavailable("boom") ): pc.apply_changelog_signals([item], TODAY, 1) self.assertEqual(item["days_without_movement"], 13) @@ -312,12 +313,12 @@ def test_a_failed_read_leaves_the_clock_alone(self): def test_an_http_error_raises_instead_of_looking_empty(self): with mock.patch.object( - pc, + jc, "open_changelog", - side_effect=pc.urllib.error.URLError("401 Unauthorized"), + side_effect=jc.urllib.error.URLError("401 Unauthorized"), ): with self.assertRaises(pc.ChangelogUnavailable): - pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) + jc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) class ChangelogTransportTest(unittest.TestCase): @@ -335,17 +336,17 @@ def __exit__(self, *exc): def call(self, payload=None, error=None): if error is not None: - patcher = mock.patch.object(pc, "open_changelog", side_effect=error) + patcher = mock.patch.object(jc, "open_changelog", side_effect=error) else: patcher = mock.patch.object( - pc, "open_changelog", return_value=self.Response(payload) + jc, "open_changelog", return_value=self.Response(payload) ) with patcher: - return pc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) + return jc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) def test_a_truncated_response_is_counted(self): with self.assertRaises(pc.ChangelogUnavailable): - self.call(error=pc.http.client.IncompleteRead(b"")) + self.call(error=jc.http.client.IncompleteRead(b"")) def test_a_non_utf8_body_is_counted(self): error = UnicodeDecodeError("utf-8", b"", 0, 1, "invalid start byte") @@ -377,10 +378,10 @@ def test_a_complete_changelog_is_read(self): self.assertEqual(self.call(payload=payload)[0], date(2026, 10, 30)) def test_a_redirect_is_refused(self): - handler = pc.NoRedirect() - with self.assertRaises(pc.urllib.error.HTTPError) as caught: + handler = jc.NoRedirect() + with self.assertRaises(jc.urllib.error.HTTPError) as caught: handler.redirect_request( - pc.urllib.request.Request("https://a.example"), + jc.urllib.request.Request("https://a.example"), None, 302, "Found", @@ -393,16 +394,16 @@ def test_a_redirect_is_refused(self): class RunJiraTest(unittest.TestCase): def test_a_timeout_is_a_pulse_error(self): with mock.patch.object( - pc.subprocess, + jc.subprocess, "run", - side_effect=pc.subprocess.TimeoutExpired("jira", 120), + side_effect=jc.subprocess.TimeoutExpired("jira", 120), ): with self.assertRaises(pc.PulseError): pc.run_jira(["issue", "list"], "jira") def test_a_missing_binary_is_a_pulse_error(self): with mock.patch.object( - pc.subprocess, "run", side_effect=FileNotFoundError("jira") + jc.subprocess, "run", side_effect=FileNotFoundError("jira") ): with self.assertRaises(pc.PulseError): pc.run_jira(["issue", "list"], "jira") @@ -417,9 +418,9 @@ def setUp(self): def api(self, server): self.config.write_text(f"server: {server}\nlogin: someone@example.com\n") - with mock.patch.object(pc.Path, "home", return_value=Path(self.tmp.name)), \ - mock.patch.dict(pc.os.environ, {"JIRA_API_TOKEN": "token"}): - return pc.jira_api() + with mock.patch.object(jc.Path, "home", return_value=Path(self.tmp.name)), \ + mock.patch.dict(jc.os.environ, {"JIRA_API_TOKEN": "token"}): + return jc.jira_api() def test_https_is_kept(self): self.assertEqual( @@ -440,7 +441,7 @@ def test_a_project_key_is_accepted(self): self.assertEqual(pc.project_key("HYPERFLEET"), "HYPERFLEET") def test_jql_is_not_a_project_key(self): - with self.assertRaises(pc.argparse.ArgumentTypeError): + with self.assertRaises(jc.argparse.ArgumentTypeError): pc.project_key("HF OR project = SECRET") @@ -650,5 +651,29 @@ def test_no_base_url_falls_back_to_bare(self): self.assertEqual(pc.ticket_ref("HYPERFLEET-1", None, "markdown"), "HYPERFLEET-1") +class LargeItemQueryTest(unittest.TestCase): + def test_done_is_filtered_by_category_not_by_status_name(self): + with mock.patch.object(pc, "run_jira", return_value="HYPERFLEET-1\n") as fake: + keys = pc.large_item_keys("HYPERFLEET", 5, "Story Points", "jira") + jql = fake.call_args.args[0][fake.call_args.args[0].index("-q") + 1] + self.assertEqual(keys, ["HYPERFLEET-1"]) + self.assertIn("statusCategory != Done", jql) + self.assertNotIn("status != Closed", jql) + + +class OpenLinksTest(unittest.TestCase): + def test_a_done_category_closes_the_link(self): + self.assertEqual(jc.open_links(["HYPERFLEET-2"], {"HYPERFLEET-2": "Done"}), []) + + def test_a_status_named_closed_but_still_in_progress_stays_open(self): + self.assertEqual( + jc.open_links(["HYPERFLEET-2"], {"HYPERFLEET-2": "In Progress"}), + ["HYPERFLEET-2"], + ) + + def test_an_unread_target_counts_as_open(self): + self.assertEqual(jc.open_links(["HYPERFLEET-2"], {}), ["HYPERFLEET-2"]) + + if __name__ == "__main__": unittest.main() diff --git a/hyperfleet-jira/tests/test_sprint_status.py b/hyperfleet-jira/tests/test_sprint_status.py index 2c547de..3e28969 100644 --- a/hyperfleet-jira/tests/test_sprint_status.py +++ b/hyperfleet-jira/tests/test_sprint_status.py @@ -22,6 +22,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +import jira_common as jc # noqa: E402 import sprint_status as ss # noqa: E402 TODAY = date(2026, 11, 3) @@ -91,7 +92,7 @@ def fake_run_jira(args, binary): return "\n".join(f"HYPERFLEET-{n}" for n in range(100, 97, -1)) + "\n" return "\n".join(f"HYPERFLEET-{n}" for n in range(200, 100, -1)) + "\n" - with mock.patch.object(ss, "run_jira", side_effect=fake_run_jira): + with mock.patch.object(jc, "run_jira", side_effect=fake_run_jira): keys = ss.search_keys("project = HYPERFLEET", "HYPERFLEET", "jira") self.assertEqual(len(keys), 103) @@ -102,7 +103,7 @@ def fake_run_jira(args, binary): def test_stops_when_a_batch_is_short(self): with mock.patch.object( - ss, "run_jira", return_value="HYPERFLEET-3\nHYPERFLEET-2\n" + jc, "run_jira", return_value="HYPERFLEET-3\nHYPERFLEET-2\n" ) as fake: keys = ss.search_keys("project = HYPERFLEET", "HYPERFLEET", "jira") self.assertEqual(keys, ["HYPERFLEET-3", "HYPERFLEET-2"]) @@ -111,16 +112,17 @@ def test_stops_when_a_batch_is_short(self): class DescribeTest(unittest.TestCase): def test_status_category_is_read_not_status_name(self): - described = ss.describe(doc(status="Closed", category="Done"), "customfield_10028", TODAY) + described = ss.describe("HYPERFLEET-100", doc(status="Closed", category="Done"), "customfield_10028", TODAY) self.assertTrue(described["is_done"]) self.assertEqual(described["category"], "Done") def test_missing_story_points_are_none_not_zero(self): - described = ss.describe(doc(sp=None), "customfield_10028", TODAY) + described = ss.describe("HYPERFLEET-100", doc(sp=None), "customfield_10028", TODAY) self.assertIsNone(described["sp"]) def test_automation_comments_are_not_movement(self): described = ss.describe( + "HYPERFLEET-100", doc(changed="2026-10-04", comments=[comment("2026-11-02", "Automation", "app")]), "customfield_10028", TODAY, @@ -130,6 +132,7 @@ def test_automation_comments_are_not_movement(self): def test_human_comment_resets_the_clock(self): described = ss.describe( + "HYPERFLEET-100", doc(changed="2026-10-04", comments=[comment("2026-11-01")]), "customfield_10028", TODAY, @@ -141,7 +144,7 @@ def test_block_link_is_not_a_blocker(self): "type": {"inward": "is blocked by", "outward": "blocks"}, "outwardIssue": {"key": "HYPERFLEET-200"}, } - blocked_by, blocks = ss.link_targets(doc(links=[link])) + blocked_by, blocks = jc.link_targets(doc(links=[link])) self.assertEqual(blocked_by, []) self.assertEqual(blocks, ["HYPERFLEET-200"]) @@ -161,9 +164,9 @@ def item(self, **overrides): def test_status_change_inside_a_category_resets_the_clock(self): subject = self.item(days_in_status=15, days_without_movement=15) - with mock.patch.object(ss, "jira_api", return_value=("https://x", "auth")), \ + with mock.patch.object(jc, "jira_api", return_value=("https://x", "auth")), \ mock.patch.object( - ss, "changelog_dates", return_value=(date(2026, 10, 30), None) + jc, "changelog_dates", return_value=(date(2026, 10, 30), None) ): ss.apply_changelog_signals([subject], TODAY, 1) self.assertEqual(subject["days_in_status"], 4) @@ -172,27 +175,27 @@ def test_status_change_inside_a_category_resets_the_clock(self): def test_assignment_resets_the_clock(self): subject = self.item() - with mock.patch.object(ss, "jira_api", return_value=("https://x", "auth")), \ + with mock.patch.object(jc, "jira_api", return_value=("https://x", "auth")), \ mock.patch.object( - ss, "changelog_dates", return_value=(None, date(2026, 10, 30)) + jc, "changelog_dates", return_value=(None, date(2026, 10, 30)) ): ss.apply_changelog_signals([subject], TODAY, 1) self.assertEqual(subject["days_without_movement"], 4) def test_new_to_backlog_is_not_movement(self): self.assertFalse( - ss.status_change_counts({"fromString": "New", "toString": "Backlog"}) + jc.status_change_counts({"fromString": "New", "toString": "Backlog"}) ) self.assertTrue( - ss.status_change_counts({"fromString": "Backlog", "toString": "In Progress"}) + jc.status_change_counts({"fromString": "Backlog", "toString": "In Progress"}) ) self.assertTrue( - ss.status_change_counts({"fromString": "In Progress", "toString": "Review"}) + jc.status_change_counts({"fromString": "In Progress", "toString": "Review"}) ) def test_missing_token_keeps_the_old_clock(self): subject = self.item() - with mock.patch.object(ss, "jira_api", return_value=None): + with mock.patch.object(jc, "jira_api", return_value=None): report = ss.apply_changelog_signals([subject], TODAY, 1) self.assertFalse(report["available"]) self.assertEqual(subject["days_without_movement"], 13) @@ -445,9 +448,9 @@ def item(self): } def test_a_failed_read_is_counted_not_hidden(self): - with mock.patch.object(ss, "jira_api", return_value=self.api), \ + with mock.patch.object(jc, "jira_api", return_value=self.api), \ mock.patch.object( - ss, "changelog_dates", + jc, "changelog_dates", side_effect=ss.ChangelogUnavailable("HYPERFLEET-1671: HTTPError"), ): report = ss.apply_changelog_signals([self.item()], TODAY, 1) @@ -456,9 +459,9 @@ def test_a_failed_read_is_counted_not_hidden(self): def test_a_failed_read_leaves_the_clock_alone(self): subject = self.item() - with mock.patch.object(ss, "jira_api", return_value=self.api), \ + with mock.patch.object(jc, "jira_api", return_value=self.api), \ mock.patch.object( - ss, "changelog_dates", side_effect=ss.ChangelogUnavailable("boom") + jc, "changelog_dates", side_effect=ss.ChangelogUnavailable("boom") ): ss.apply_changelog_signals([subject], TODAY, 1) self.assertEqual(subject["days_without_movement"], 13) @@ -474,9 +477,9 @@ def setUp(self): def api(self, server): self.config.write_text(f"server: {server}\nlogin: someone@example.com\n") - with mock.patch.object(ss.Path, "home", return_value=Path(self.tmp.name)), \ + with mock.patch.object(jc.Path, "home", return_value=Path(self.tmp.name)), \ mock.patch.dict(os.environ, {"JIRA_API_TOKEN": "token"}): - return ss.jira_api() + return jc.jira_api() def test_https_is_kept(self): self.assertEqual( @@ -505,21 +508,21 @@ def __exit__(self, *exc): def call(self, payload=None, error=None): if error is not None: - patcher = mock.patch.object(ss, "open_changelog", side_effect=error) + patcher = mock.patch.object(jc, "open_changelog", side_effect=error) else: patcher = mock.patch.object( - ss, "open_changelog", return_value=self.Response(payload) + jc, "open_changelog", return_value=self.Response(payload) ) with patcher: - return ss.changelog_dates("HYPERFLEET-1", "acc-1", self.api) + return jc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) def test_a_network_error_is_counted(self): with self.assertRaises(ss.ChangelogUnavailable): - self.call(error=ss.urllib.error.URLError("401 Unauthorized")) + self.call(error=jc.urllib.error.URLError("401 Unauthorized")) def test_a_truncated_response_is_counted(self): with self.assertRaises(ss.ChangelogUnavailable): - self.call(error=ss.http.client.IncompleteRead(b"")) + self.call(error=jc.http.client.IncompleteRead(b"")) def test_a_non_utf8_body_is_counted(self): error = UnicodeDecodeError("utf-8", b"", 0, 1, "invalid start byte") @@ -551,10 +554,10 @@ def test_a_complete_changelog_is_read(self): self.assertEqual(self.call(payload=payload)[0], date(2026, 10, 30)) def test_a_redirect_is_refused(self): - handler = ss.NoRedirect() - with self.assertRaises(ss.urllib.error.HTTPError) as caught: + handler = jc.NoRedirect() + with self.assertRaises(jc.urllib.error.HTTPError) as caught: handler.redirect_request( - ss.urllib.request.Request("https://a.example"), + jc.urllib.request.Request("https://a.example"), None, 302, "Found", @@ -569,9 +572,58 @@ def test_a_project_key_is_accepted(self): self.assertEqual(ss.project_key("HYPERFLEET"), "HYPERFLEET") def test_jql_is_not_a_project_key(self): - with self.assertRaises(ss.argparse.ArgumentTypeError): + with self.assertRaises(jc.argparse.ArgumentTypeError): ss.project_key("HF OR project = SECRET") +class BaselineTest(unittest.TestCase): + """The baseline measures the previous sprint at its own end date.""" + + sprint = { + "id": "66536", + "name": "Hyperfleet Sprint 18", + "start": "2026-10-12", + "end": "2026-10-25", + } + + def run_baseline(self, docs): + with mock.patch.object(ss, "search_keys", return_value=[d["key"] for d in docs]), \ + mock.patch.object(ss, "fetch_all", return_value={d["key"]: d for d in docs}): + return ss.baseline_for( + self.sprint, + "HYPERFLEET", + "customfield_10028", + "jira", + 1, + TODAY, + ) + + def test_counts_only_work_closed_by_the_sprint_end(self): + baseline = self.run_baseline( + [ + doc("HYPERFLEET-1", sp=3, status="Done", category="Done", changed="2026-10-20"), + doc("HYPERFLEET-2", sp=5, status="Closed", category="Done", changed="2026-11-02"), + doc("HYPERFLEET-3", sp=2, status="In Progress", category="In Progress", changed="2026-10-20"), + ] + ) + self.assertEqual(baseline["committed_sp"], 10) + self.assertEqual(baseline["delivered_sp"], 3) + self.assertEqual(baseline["percent"], 30.0) + self.assertEqual(baseline["end"], "2026-10-25") + + def test_work_closed_on_the_last_day_still_counts(self): + baseline = self.run_baseline( + [doc("HYPERFLEET-1", sp=5, status="Closed", category="Done", changed="2026-10-25")] + ) + self.assertEqual(baseline["delivered_sp"], 5) + + def test_an_open_item_is_never_delivered(self): + baseline = self.run_baseline( + [doc("HYPERFLEET-1", sp=5, status="In Progress", category="In Progress", changed="2026-10-20")] + ) + self.assertEqual(baseline["delivered_sp"], 0) + self.assertEqual(baseline["percent"], 0.0) + + if __name__ == "__main__": unittest.main() From f02010e7ae228ab27237275ff09bf7caa1e6c8fd Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 15:03:03 -0300 Subject: [PATCH 5/9] HYPERFLEET-1890 - fix(hyperfleet-jira): scope the pulse queue to the reported sprint build reports the sprint returned by active_sprint, but large_item_keys queried sprint in openSprints(), so with more than one active sprint the queue could mix in issues from another one. Pass the selected sprint id into the query. Add a test that asserts the JQL names the sprint and does not use openSprints(). --- hyperfleet-jira/scripts/pulse_check.py | 10 +++++++--- hyperfleet-jira/tests/test_pulse_check.py | 11 ++++++++++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/hyperfleet-jira/scripts/pulse_check.py b/hyperfleet-jira/scripts/pulse_check.py index 7249fd8..cf26a78 100755 --- a/hyperfleet-jira/scripts/pulse_check.py +++ b/hyperfleet-jira/scripts/pulse_check.py @@ -66,9 +66,11 @@ def cell(text: str) -> str: return prose(text).replace("|", "\\|") -def large_item_keys(project: str, min_sp: int, sp_field_name: str, binary: str) -> list[str]: +def large_item_keys( + project: str, sprint_id: str, min_sp: int, sp_field_name: str, binary: str +) -> list[str]: jql = ( - f'project = {project} AND sprint in openSprints() ' + f'project = {project} AND sprint = {sprint_id} ' f'AND "{sp_field_name}" >= {min_sp} AND {OPEN_STATUS_JQL}' ) out = run_jira( @@ -151,7 +153,9 @@ def suggested_ask(item: dict) -> str: def build(args) -> dict: today = parse_date(args.today) if args.today else datetime.now(timezone.utc).date() sprint = active_sprint(args.project, args.jira) - keys = large_item_keys(args.project, args.min_sp, args.sp_field_name, args.jira) + keys = large_item_keys( + args.project, sprint["id"], args.min_sp, args.sp_field_name, args.jira + ) docs = fetch_all(keys, args.project, args.jira, args.jobs) items = [] diff --git a/hyperfleet-jira/tests/test_pulse_check.py b/hyperfleet-jira/tests/test_pulse_check.py index fc03fd9..a69d76b 100644 --- a/hyperfleet-jira/tests/test_pulse_check.py +++ b/hyperfleet-jira/tests/test_pulse_check.py @@ -654,12 +654,21 @@ def test_no_base_url_falls_back_to_bare(self): class LargeItemQueryTest(unittest.TestCase): def test_done_is_filtered_by_category_not_by_status_name(self): with mock.patch.object(pc, "run_jira", return_value="HYPERFLEET-1\n") as fake: - keys = pc.large_item_keys("HYPERFLEET", 5, "Story Points", "jira") + keys = pc.large_item_keys( + "HYPERFLEET", "66537", 5, "Story Points", "jira" + ) jql = fake.call_args.args[0][fake.call_args.args[0].index("-q") + 1] self.assertEqual(keys, ["HYPERFLEET-1"]) self.assertIn("statusCategory != Done", jql) self.assertNotIn("status != Closed", jql) + def test_the_query_is_scoped_to_the_reported_sprint(self): + with mock.patch.object(pc, "run_jira", return_value="") as fake: + pc.large_item_keys("HYPERFLEET", "66537", 5, "Story Points", "jira") + jql = fake.call_args.args[0][fake.call_args.args[0].index("-q") + 1] + self.assertIn("sprint = 66537", jql) + self.assertNotIn("openSprints()", jql) + class OpenLinksTest(unittest.TestCase): def test_a_done_category_closes_the_link(self): From 55b6cc372cbf030234d6978c09bbe1a3aa9c2039 Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 15:14:39 -0300 Subject: [PATCH 6/9] HYPERFLEET-1890 - fix(hyperfleet-jira): link every ticket key in the sprint reports The reports linked an item's own key and left the blocker keys bare, so the one line a lead acts on - the blocked item - ended in keys nobody could click. Link every key instead: the blocker keys in sprint_status, and in pulse_check the blockers named in an Ask plus the prose lines (No action, Escalation, assign these first). suggested_ask takes an optional ref callable, defaulting to the bare key, so the ask stays testable and a log still reads. Update both commands: links are the default, bare is a whole-report choice for destinations that cannot render them. --- .../commands/sprint-pulse-check.md | 14 ++--- hyperfleet-jira/commands/sprint-status.md | 12 ++-- hyperfleet-jira/scripts/pulse_check.py | 43 ++++++++++---- hyperfleet-jira/scripts/sprint_status.py | 2 +- hyperfleet-jira/tests/test_pulse_check.py | 58 ++++++++++++++++++- 5 files changed, 103 insertions(+), 26 deletions(-) diff --git a/hyperfleet-jira/commands/sprint-pulse-check.md b/hyperfleet-jira/commands/sprint-pulse-check.md index a866da8..01c797b 100644 --- a/hyperfleet-jira/commands/sprint-pulse-check.md +++ b/hyperfleet-jira/commands/sprint-pulse-check.md @@ -68,7 +68,7 @@ And two rules that come from running the check: ## Output Format -One screen. Slack-ready. Ticket keys are links; keys in prose stay bare. No progress bar. +One screen. Slack-ready. Every ticket key is a link. No progress bar. ```text Pulse check - Hyperfleet Sprint 19, 2026-11-03 @@ -81,11 +81,11 @@ Nudge queue (5 of 7 owned large items need action): | [HYPERFLEET-1413](https:///browse/HYPERFLEET-1413) | Verify N-1 to N operator upgrades converge the API operand | Tirth | 5 | In Progress · 20d | Propose a split with dates, or re-scope | | [HYPERFLEET-1616](https:///browse/HYPERFLEET-1616) | SPIKE: Extend Prow testing to support OLM installs classic and v1 | Mallory | 5 | Backlog · 60d (since 09-04) | Post the decision note this week or drop from the sprint | -No action: HYPERFLEET-1671 (4d, assigned 10-30), HYPERFLEET-1751 (1d) +No action: [HYPERFLEET-1671](https:///browse/HYPERFLEET-1671) (4d, assigned 10-30), [HYPERFLEET-1751](https:///browse/HYPERFLEET-1751) (1d) Assignment gap: 17 items / 85 SP have no owner - sizes present: 5 SP -- assign these first: HYPERFLEET-XXXX (blocks 7), HYPERFLEET-XXXX (blocks 4) +- assign these first: [HYPERFLEET-XXXX](https:///browse/HYPERFLEET-XXXX) (blocks 7), [HYPERFLEET-XXXX](https:///browse/HYPERFLEET-XXXX) (blocks 4) Concentration: Phuongnhat holds 3 of 7 owned items (21 of 41 SP) @@ -96,18 +96,18 @@ Next pulse: 2026-11-05 Rules for the output: - **Never wrap the report in a code fence for chat or TUI.** The fence in the template is illustrative: inside it the links and emphasis reach the reader as literal characters. Use the fence only when the destination is Slack, email, or a log file, and say which one you are formatting for. -- **Print the base URL once, under the title.** It is the fallback for the keys that stay bare in prose. The script emits it from the `server:` entry in `~/.config/.jira/.config.yml`; never hardcode it. -- **Ticket keys are links.** The script emits `[HYPERFLEET-XXXX](url)` by default; pass `--link-style slack` for Slack (``) and `--link-style bare` for a log or a plain-text paste. Never mix two styles in one output. +- **Print the base URL once, under the title.** It documents where the links point; it is not a fallback for unlinked keys. The script emits it from the `server:` entry in `~/.config/.jira/.config.yml`; never hardcode it. +- **Every ticket key is a link**, in the table and in the prose lines below it (`No action`, `Escalation`, `assign these first`, and the blocker named in an `Ask`). The script renders all of them for you; pass `--link-style slack` for Slack (``) and `--link-style bare` for a log or a plain-text paste. Never mix two styles in one output. - **One table row per item, six columns, `Ask` last.** `Ticket | Title | Owner | SP | Status · age | Ask`. No second row, no empty cell: an `Ask` row under the data row squeezes the text into the first column, and Markdown has no `colspan` to fix it. `Ask` sits last because the last column is the one that grows, so a long ask wraps at the right edge instead of widening the table from the left. - **Status and age share a column.** "Review · 12d" is one thought for the reader. Splitting it into two columns costs width and buys nothing. - **Keep the title and the SP.** Without the title the ask loses its referent; without the SP an 8-point item gets the same nudge as a 5. -- The **Ask** names the next action, not the problem, and it starts with a verb: `Ask Martin to approve or reject HYPERFLEET-1636 (Review 7d); assign HYPERFLEET-1523`, `Ask a reviewer to approve or reject`, `Start this week or drop from the sprint`, `Post a start date and the first step on the ticket`. +- The **Ask** names the next action, not the problem, and it starts with a verb: `Ask Martin to approve or reject [HYPERFLEET-1636](url) (Review 7d); assign [HYPERFLEET-1523](url)`, `Ask a reviewer to approve or reject`, `Start this week or drop from the sprint`, `Post a start date and the first step on the ticket`. - **The verb comes from a closed set:** `ask` (approve/reject, status, start or drop), `assign`, `post`, `start`, `propose` (a split), `confirm` (a date). A closed set keeps the column scannable and countable, and it bounds the hand rewrite in step 4 to the specifics - who, which PR, which blocker - never to the choice of action. - **Never restate the item's own age in the Ask.** It is in the `Status · age` cell beside it; repeating it costs width and produces "20+ days: 20+ days". A blocker's age does appear, because that clock is not in the table. - **The verb follows the state, not the age alone:** blocked items name the blocker's move, `Review` asks a reviewer for a decision, `In Progress` asks for evidence on the ticket, and unstarted work asks for a date; a spike asks for the decision note, never for a start date. - Items in good standing stay visible only in the single "No action" line, never as table rows. - In the `Status · age` cell, `(assigned MM-DD)` marks a clock shortened by a reassignment and `(since MM-DD)` marks a Backlog item with no start. Never show both. -- A blocker's age is its own last workflow transition, not the blocked item's. A blocker in `Review` leads the ask and names its reviewer (`Ask Martin to approve or reject HYPERFLEET-1636 (Review 7d)`); an unowned blocker becomes `assign HYPERFLEET-1523`, because there is nobody to ask. +- A blocker's age is its own last workflow transition, not the blocked item's. A blocker in `Review` leads the ask and names its reviewer (`Ask Martin to approve or reject [HYPERFLEET-1636](url) (Review 7d)`); an unowned blocker becomes `assign [HYPERFLEET-1523](url)`, because there is nobody to ask. - **Say when the signal is partial.** The command reads JSON, so the script's own text warning never appears. If `changelog_signal.failed` is non-zero, add one line under the queue: `Signal: partial - N of M changelog reads failed; those items use the status category date`. If `changelog_signal.available` is false, add: `Signal: partial - no JIRA_API_TOKEN, so movement ignores exact status changes and assignments`. - State the movement definition in every output. Without it the numbers start arguments. - Date the output, and print the next pulse date, so a stale copy is recognizable at a glance. diff --git a/hyperfleet-jira/commands/sprint-status.md b/hyperfleet-jira/commands/sprint-status.md index 36a4421..75f2229 100644 --- a/hyperfleet-jira/commands/sprint-status.md +++ b/hyperfleet-jira/commands/sprint-status.md @@ -59,12 +59,12 @@ Comprehensive sprint health report for team leads and scrum masters. ## Ticket References -Every key in the report must be resolvable, and no table may turn into link soup. +Every ticket key in the report is a link, and the same key is linked every time it appears. -- Print the base URL once, in Sprint Overview. The script emits it as `Jira: /browse/`, read from the `server:` entry in `~/.config/.jira/.config.yml`. It is the fallback for every key that stays bare. -- Link each item's own key once, at the start of its Blockers, Highest-priority, Stale or Carry-Over line. That is where the reader acts. Blocker keys inside the same line stay bare: that is what keeps a long line readable. +- Print the base URL once, in Sprint Overview. The script emits it as `Jira: /browse/`, read from the `server:` entry in `~/.config/.jira/.config.yml`. It documents where the links point; it is not a fallback for unlinked keys. +- Link the item's own key at the start of its Blockers, Highest-priority, Stale or Carry-Over line, and link every blocker key inside that line too. A blocked item is actionable only through its blockers, so a bare blocker key is a dead end on the line where the reader decides. - The report's tables carry no ticket keys. If a table ever lists tickets, link the key there too. -- Never link the same ticket twice in the same section. +- A key repeated across sections is linked in each of them: the reader arrives at a section, not at the document. Match the syntax to the destination, because only one of the three renders all of them: @@ -74,6 +74,8 @@ Match the syntax to the destination, because only one of the three renders all o | Slack | `` | run the script with `--link-style slack` | | Plain log / paste | `HYPERFLEET-XXXX` | run the script with `--link-style bare` | +Links are the default, not a decoration. When the destination cannot render them, say so in the reply and switch the whole report to `--link-style bare`; never strip the links from part of the report. + ## Output Format The script's `--format markdown` output **is** the report: present it as Markdown, then add Recommendations. @@ -106,7 +108,7 @@ Progress: [=====> ] X% by SP (X of X) | X% by count (X of X) ### Risk Assessment #### Blocked by open work -- KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - blocked by KEY (Status), KEY (Status) +- KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - blocked by [KEY](url) (Status), [KEY](url) (Status) #### Highest-priority open items - KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - [X days without movement] diff --git a/hyperfleet-jira/scripts/pulse_check.py b/hyperfleet-jira/scripts/pulse_check.py index cf26a78..b4c305e 100755 --- a/hyperfleet-jira/scripts/pulse_check.py +++ b/hyperfleet-jira/scripts/pulse_check.py @@ -100,7 +100,7 @@ def is_spike(item: dict) -> bool: return item.get("summary", "").lstrip().upper().startswith(("SPIKE", "[SPIKE]")) -def suggested_ask(item: dict) -> str: +def suggested_ask(item: dict, ref=None) -> str: """One imperative per item: verb first, then who and what artifact. The verb comes from a fixed set - ask to approve/reject, assign, unblock, @@ -108,7 +108,12 @@ def suggested_ask(item: dict) -> str: The item's own age lives in the `Status . age` cell, so the text never repeats it; a blocker"s age does appear, because that clock is not in the table and it is what makes the blocker urgent or not. + + `ref` renders a key for the destination, so a blocker named in the ask is a + link like every other key in the report. It defaults to the bare key, which + keeps the ask readable in a test and in a log. """ + ref = ref or (lambda key: key) if item["open_blockers"]: # A blocker in Review is the one an ask can move today, so it leads. detail = sorted( @@ -121,15 +126,19 @@ def suggested_ask(item: dict) -> str: when = f" {days}d" if days is not None else "" if d["status"] == "Review" and d.get("owner"): clauses.append( - f"ask {d['owner'].split()[0]} to approve or reject {d['key']} " + f"ask {d['owner'].split()[0]} to approve or reject {ref(d['key'])} " f"(Review{when})" ) elif not d.get("owner"): - clauses.append(f"assign {d['key']}") + clauses.append(f"assign {ref(d['key'])}") elif d["status"] == "In Progress": - clauses.append(f"ask {d['owner'].split()[0]} for the status of {d['key']}") + clauses.append( + f"ask {d['owner'].split()[0]} for the status of {ref(d['key'])}" + ) else: - clauses.append(f"ask {d['owner'].split()[0]} to start or drop {d['key']}") + clauses.append( + f"ask {d['owner'].split()[0]} to start or drop {ref(d['key'])}" + ) shown = "; ".join(clauses[:2]) more = f" (+{len(clauses) - 2} more)" if len(clauses) > 2 else "" return shown[0].upper() + shown[1:] + more @@ -190,6 +199,11 @@ def build(args) -> dict: file=sys.stderr, ) + base_url = jira_base_url() + + def ref(key: str) -> str: + return ticket_ref(key, base_url, args.link_style) + for item in items: item["open_blockers"] = open_links(item["blocked_by"], category_of) item["blocked"] = bool(item["open_blockers"]) @@ -203,7 +217,7 @@ def build(args) -> dict: for k in item["open_blockers"] ] item["blocks_open"] = open_links(item["blocks"], category_of) - item["ask"] = suggested_ask(item) + item["ask"] = suggested_ask(item, ref) owned = [i for i in items if i["owner"]] unowned = [i for i in items if not i["owner"]] @@ -231,7 +245,7 @@ def build(args) -> dict: return { "generated_for": today.isoformat(), "project": args.project, - "jira_base_url": jira_base_url(), + "jira_base_url": base_url, "link_style": args.link_style, "sprint": sprint, "definition": ( @@ -290,6 +304,10 @@ def render_text(data: dict) -> str: queue = data["queue"] base_url = data.get("jira_base_url") style = data.get("link_style", "markdown") + + def ref(key: str) -> str: + return ticket_ref(key, base_url, style) + lines.append( f"Nudge queue ({len(queue)} of {totals['owned']['items']} owned large items need action):" ) @@ -316,17 +334,19 @@ def render_text(data: dict) -> str: if data["no_action"]: entries = [] for i in data["no_action"]: - entry = f"{i['key']} ({i['days_without_movement']}d" + entry = f"{ref(i['key'])} ({i['days_without_movement']}d" if assignment_is_binding(i) and i.get("assigned"): entry += f", assigned {i['assigned'][5:]}" entries.append(f"{entry})") lines.append(f"\nNo action: {', '.join(entries)}") if data["escalation_20d"]: - lines.append(f"\nEscalation 20+ days: {', '.join(data['escalation_20d'])}" + keys = ", ".join(ref(key) for key in data["escalation_20d"]) + lines.append(f"\nEscalation 20+ days: {keys}" " — lead decides: start, split, re-scope or drop") if data["escalation_excluded_blocked"]: - lines.append(f"(excluded as blocked: {', '.join(data['escalation_excluded_blocked'])})") + keys = ", ".join(ref(key) for key in data["escalation_excluded_blocked"]) + lines.append(f"(excluded as blocked: {keys})") gap = data["assignment_gap"] if gap["items"]: @@ -335,7 +355,8 @@ def render_text(data: dict) -> str: lines.append(f"- sizes present: {sizes}") if gap["blocking_other_work"]: top = ", ".join( - f"{o['key']} (blocks {o['blocks_open']})" for o in gap["blocking_other_work"][:4] + f"{ref(o['key'])} (blocks {o['blocks_open']})" + for o in gap["blocking_other_work"][:4] ) lines.append(f"- assign these first: {top}") diff --git a/hyperfleet-jira/scripts/sprint_status.py b/hyperfleet-jira/scripts/sprint_status.py index c53968c..10631f5 100755 --- a/hyperfleet-jira/scripts/sprint_status.py +++ b/hyperfleet-jira/scripts/sprint_status.py @@ -587,7 +587,7 @@ def ref(key: str) -> str: ) for item in blockers["blocked"][:10]: detail = ", ".join( - f"{d['key']} ({d['status']})" for d in item["blocker_detail"] + f"{ref(d['key'])} ({d['status']})" for d in item["blocker_detail"] if d["category"] != "Done" ) owner = item["owner"] or "UNASSIGNED" diff --git a/hyperfleet-jira/tests/test_pulse_check.py b/hyperfleet-jira/tests/test_pulse_check.py index a69d76b..6e317cc 100644 --- a/hyperfleet-jira/tests/test_pulse_check.py +++ b/hyperfleet-jira/tests/test_pulse_check.py @@ -458,6 +458,25 @@ def ask(self, status, days, blockers=None, summary="A large item"): } return pc.suggested_ask(item) + def test_the_blocker_in_the_ask_is_a_link(self): + ask = pc.suggested_ask( + { + "summary": "A large item", + "status": "Backlog", + "days_without_movement": 3, + "open_blockers": ["HYPERFLEET-1636"], + "blocker_detail": [ + {"key": "HYPERFLEET-1636", "status": "Review", "owner": "Martin Liptak"} + ], + }, + lambda key: pc.ticket_ref(key, "https://example.atlassian.net/browse/", "markdown"), + ) + self.assertIn( + "approve or reject [HYPERFLEET-1636]" + "(https://example.atlassian.net/browse/HYPERFLEET-1636)", + ask, + ) + def test_blocked_item_names_the_blocker_and_the_move(self): ask = self.ask("Backlog", 70, ["HYPERFLEET-1636"]) self.assertIn("HYPERFLEET-1636", ask) @@ -568,7 +587,11 @@ def test_no_action_line_carries_the_assignment_date(self): "days_in_status": 47, "days_since_comment": 13, "days_since_assignment": 4, "assigned": "2026-10-30"} ] - self.assertIn("No action: HYPERFLEET-1671 (4d, assigned 10-30)", pc.render_text(data)) + self.assertIn( + "No action: [HYPERFLEET-1671](https://example.atlassian.net/browse/HYPERFLEET-1671)" + " (4d, assigned 10-30)", + pc.render_text(data), + ) def test_no_action_line_hides_an_assignment_that_is_not_the_binding_signal(self): data = self.data() @@ -577,7 +600,10 @@ def test_no_action_line_hides_an_assignment_that_is_not_the_binding_signal(self) "days_in_status": 30, "days_since_comment": 1, "days_since_assignment": 4, "assigned": "2026-10-30"} ] - self.assertIn("No action: HYPERFLEET-1751 (1d)", pc.render_text(data)) + self.assertIn( + "No action: [HYPERFLEET-1751](https://example.atlassian.net/browse/HYPERFLEET-1751) (1d)", + pc.render_text(data), + ) self.assertNotIn("assigned 10-30", pc.render_text(data)) def test_one_table_row_per_item_with_the_ask_last(self): @@ -597,6 +623,34 @@ def test_a_pipe_in_the_summary_does_not_break_the_row(self): row = [line for line in pc.render_text(data).splitlines() if "HYPERFLEET-1)" in line][0] self.assertEqual(row.count("|") - row.count("\\|"), 7) + def test_prose_keys_are_links(self): + data = self.data() + data["escalation_20d"] = ["HYPERFLEET-2"] + data["assignment_gap"] = { + "items": 1, + "sp": 5, + "sizes": [5], + "blocking_other_work": [{"key": "HYPERFLEET-3", "sp": 5, "blocks_open": 7}], + } + text = pc.render_text(data) + self.assertIn( + "Escalation 20+ days: [HYPERFLEET-2](https://example.atlassian.net/browse/HYPERFLEET-2)", + text, + ) + self.assertIn( + "assign these first: [HYPERFLEET-3](https://example.atlassian.net/browse/HYPERFLEET-3)" + " (blocks 7)", + text, + ) + + def test_bare_style_leaves_every_key_plain(self): + data = self.data() + data["link_style"] = "bare" + data["escalation_20d"] = ["HYPERFLEET-2"] + text = pc.render_text(data) + self.assertIn("Escalation 20+ days: HYPERFLEET-2", text) + self.assertNotIn("](", text) + def test_a_failed_changelog_read_is_named_in_the_report(self): data = self.data() data["changelog_signal"] = { From d33cac87a2771613e7ba602c846d93486be76bea Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 15:20:48 -0300 Subject: [PATCH 7/9] HYPERFLEET-1890 - fix(hyperfleet-jira): scope the pulse link promise to the text format The command runs `--format json`, where a queue item carries a bare key and the payload carries `jira_base_url` and `link_style`; only `--format text` prints the keys already rendered. The rule now says which of the two does what and how to render a key from JSON, and it keeps the JSON invocation, which is what the lead recomputes from. Also note that the `ask` string arrives rendered and must not be re-rendered. --- hyperfleet-jira/commands/sprint-pulse-check.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hyperfleet-jira/commands/sprint-pulse-check.md b/hyperfleet-jira/commands/sprint-pulse-check.md index 01c797b..dadcbe5 100644 --- a/hyperfleet-jira/commands/sprint-pulse-check.md +++ b/hyperfleet-jira/commands/sprint-pulse-check.md @@ -97,7 +97,7 @@ Rules for the output: - **Never wrap the report in a code fence for chat or TUI.** The fence in the template is illustrative: inside it the links and emphasis reach the reader as literal characters. Use the fence only when the destination is Slack, email, or a log file, and say which one you are formatting for. - **Print the base URL once, under the title.** It documents where the links point; it is not a fallback for unlinked keys. The script emits it from the `server:` entry in `~/.config/.jira/.config.yml`; never hardcode it. -- **Every ticket key is a link**, in the table and in the prose lines below it (`No action`, `Escalation`, `assign these first`, and the blocker named in an `Ask`). The script renders all of them for you; pass `--link-style slack` for Slack (``) and `--link-style bare` for a log or a plain-text paste. Never mix two styles in one output. +- **Every ticket key is a link**, in the table and in the prose lines below it (`No action`, `Escalation`, `assign these first`). `--format text` prints them already rendered; this command reads `--format json`, where the key stays bare and the payload carries `jira_base_url` and `link_style` instead, so render each key yourself: `[HYPERFLEET-XXXX](HYPERFLEET-XXXX)` for chat or TUI, `` for `--link-style slack`, the bare key for `--link-style bare`. Never mix two styles in one output. Do not re-render text that already arrives rendered - the `Ask` string is composed by the script and comes with its keys in the chosen style. - **One table row per item, six columns, `Ask` last.** `Ticket | Title | Owner | SP | Status · age | Ask`. No second row, no empty cell: an `Ask` row under the data row squeezes the text into the first column, and Markdown has no `colspan` to fix it. `Ask` sits last because the last column is the one that grows, so a long ask wraps at the right edge instead of widening the table from the left. - **Status and age share a column.** "Review · 12d" is one thought for the reader. Splitting it into two columns costs width and buys nothing. - **Keep the title and the SP.** Without the title the ask loses its referent; without the SP an 8-point item gets the same nudge as a 5. From 9a9118e2a2e425adba80fcb8991d5c121c50ca14 Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 15:20:29 -0300 Subject: [PATCH 8/9] HYPERFLEET-1890 - feat(hyperfleet-jira): link the pull requests of items in review The reports linked tickets and stopped there, but for an item in Review the next click is the pull request, not the ticket. Both commands now read the remote links Jira keeps for the issue and append the pull requests the team attached: - sprint_status: `(7d) - PR [#177](url)` at the end of the risk line - pulse_check: inside the Ask, where the reviewer acts Only `/pull/` URLs count: the development panel stores branches and commits in the same shape. The panel carries the link, not the state, so a listed pull request may already be merged; the doc says so. Only Review items are looked up, since no other status has an artefact to review. A failed read is counted, not hidden: the Method section and the pulse signal line name it, next to the changelog signal they sit beside. --no-prs skips the lookup for a run that must not touch the API. --- .../commands/sprint-pulse-check.md | 7 +- hyperfleet-jira/commands/sprint-status.md | 11 +- hyperfleet-jira/scripts/jira_common.py | 118 ++++++++++++++++++ hyperfleet-jira/scripts/pulse_check.py | 34 +++++ hyperfleet-jira/scripts/sprint_status.py | 34 ++++- hyperfleet-jira/tests/test_pulse_check.py | 8 ++ hyperfleet-jira/tests/test_sprint_status.py | 94 ++++++++++++++ 7 files changed, 296 insertions(+), 10 deletions(-) diff --git a/hyperfleet-jira/commands/sprint-pulse-check.md b/hyperfleet-jira/commands/sprint-pulse-check.md index dadcbe5..7a117fc 100644 --- a/hyperfleet-jira/commands/sprint-pulse-check.md +++ b/hyperfleet-jira/commands/sprint-pulse-check.md @@ -32,9 +32,9 @@ This command produces a short nudge queue. It is not a sprint status report: it ```bash python3 "$PULSE" --project HYPERFLEET --format json ``` - Options: `--today YYYY-MM-DD` for a reproducible run, `--format text` for a ready-to-paste block, `--min-sp` and `--max-rows` to move the thresholds, `--link-style markdown|slack|bare` to match the destination, `--next-pulse YYYY-MM-DD` to print the next scheduled pulse (omit it when the lead has not scheduled one, and the output says "to be scheduled"). + Options: `--today YYYY-MM-DD` for a reproducible run, `--format text` for a ready-to-paste block, `--min-sp` and `--max-rows` to move the thresholds, `--link-style markdown|slack|bare` to match the destination, `--next-pulse YYYY-MM-DD` to print the next scheduled pulse (omit it when the lead has not scheduled one, and the output says "to be scheduled"), `--no-prs` to skip the pull request lookup. - The script reads the active sprint, the open items at or above `--min-sp`, the movement signals, and the status of every link target. It returns the queue, the escalation buckets, the assignment gap and the concentration. + The script reads the active sprint, the open items at or above `--min-sp`, the movement signals, the status of every link target, and the pull requests Jira links to the items in `Review`. It returns the queue, the escalation buckets, the assignment gap and the concentration. 3. **Do not recompute by hand.** The script's `days_without_movement`, `open_blockers` and `assignment_gap` are the numbers of record. If a value looks wrong, fix the script. @@ -98,6 +98,7 @@ Rules for the output: - **Never wrap the report in a code fence for chat or TUI.** The fence in the template is illustrative: inside it the links and emphasis reach the reader as literal characters. Use the fence only when the destination is Slack, email, or a log file, and say which one you are formatting for. - **Print the base URL once, under the title.** It documents where the links point; it is not a fallback for unlinked keys. The script emits it from the `server:` entry in `~/.config/.jira/.config.yml`; never hardcode it. - **Every ticket key is a link**, in the table and in the prose lines below it (`No action`, `Escalation`, `assign these first`). `--format text` prints them already rendered; this command reads `--format json`, where the key stays bare and the payload carries `jira_base_url` and `link_style` instead, so render each key yourself: `[HYPERFLEET-XXXX](HYPERFLEET-XXXX)` for chat or TUI, `` for `--link-style slack`, the bare key for `--link-style bare`. Never mix two styles in one output. Do not re-render text that already arrives rendered - the `Ask` string is composed by the script and comes with its keys in the chosen style. +- **A pull request is a link too.** For an item in `Review` the script appends the pull requests Jira links to the ticket: `Ask a reviewer to approve or reject PR [#177](url)` when the ask is generic, `- PR [#177](url)` after a named blocker. It rides in the `Ask`, already rendered in the chosen style, and is not a seventh column - `Ask` is where the reviewer acts. The development panel carries the link and not the state, so the PR may already be merged; and a branch or a commit is not shown, because it is not what a reviewer opens. If the lookup fails, the signal line below the queue says so. - **One table row per item, six columns, `Ask` last.** `Ticket | Title | Owner | SP | Status · age | Ask`. No second row, no empty cell: an `Ask` row under the data row squeezes the text into the first column, and Markdown has no `colspan` to fix it. `Ask` sits last because the last column is the one that grows, so a long ask wraps at the right edge instead of widening the table from the left. - **Status and age share a column.** "Review · 12d" is one thought for the reader. Splitting it into two columns costs width and buys nothing. - **Keep the title and the SP.** Without the title the ask loses its referent; without the SP an 8-point item gets the same nudge as a 5. @@ -108,7 +109,7 @@ Rules for the output: - Items in good standing stay visible only in the single "No action" line, never as table rows. - In the `Status · age` cell, `(assigned MM-DD)` marks a clock shortened by a reassignment and `(since MM-DD)` marks a Backlog item with no start. Never show both. - A blocker's age is its own last workflow transition, not the blocked item's. A blocker in `Review` leads the ask and names its reviewer (`Ask Martin to approve or reject [HYPERFLEET-1636](url) (Review 7d)`); an unowned blocker becomes `assign [HYPERFLEET-1523](url)`, because there is nobody to ask. -- **Say when the signal is partial.** The command reads JSON, so the script's own text warning never appears. If `changelog_signal.failed` is non-zero, add one line under the queue: `Signal: partial - N of M changelog reads failed; those items use the status category date`. If `changelog_signal.available` is false, add: `Signal: partial - no JIRA_API_TOKEN, so movement ignores exact status changes and assignments`. +- **Say when the signal is partial.** The command reads JSON, so the script's own text warning never appears. If `changelog_signal.failed` is non-zero, add one line under the queue: `Signal: partial - N of M changelog reads failed; those items use the status category date`. If `changelog_signal.available` is false, add: `Signal: partial - no JIRA_API_TOKEN, so movement ignores exact status changes and assignments`. If `pr_signal.failed` is non-zero, add: `Signal: partial - N of M pull request reads failed; those items carry no pull request link`. - State the movement definition in every output. Without it the numbers start arguments. - Date the output, and print the next pulse date, so a stale copy is recognizable at a glance. diff --git a/hyperfleet-jira/commands/sprint-status.md b/hyperfleet-jira/commands/sprint-status.md index 75f2229..5ddcb27 100644 --- a/hyperfleet-jira/commands/sprint-status.md +++ b/hyperfleet-jira/commands/sprint-status.md @@ -30,9 +30,9 @@ Comprehensive sprint health report for team leads and scrum masters. ```bash python3 "$SPRINT" --project HYPERFLEET --format markdown ``` - Options: `--today YYYY-MM-DD` for a reproducible run, `--sprint ` to report on a sprint other than the active one, `--stale-days` to move the staleness threshold, `--blocker-priority` to change which priority counts as top, `--link-style markdown|slack|bare` to match the destination, `--no-baseline` to skip the previous sprint lookup. + Options: `--today YYYY-MM-DD` for a reproducible run, `--sprint ` to report on a sprint other than the active one, `--stale-days` to move the staleness threshold, `--blocker-priority` to change which priority counts as top, `--link-style markdown|slack|bare` to match the destination, `--no-baseline` to skip the previous sprint lookup, `--no-prs` to skip the pull request lookup. - The script reads the sprint metadata and goal, every issue in the sprint, the story points, the movement signals, the open blockers, the previous sprint's baseline, and a capacity projection. The baseline's delivered points are measured at the previous sprint's end date, so work closed later is not credited to it. It returns the report in one document. + The script reads the sprint metadata and goal, every issue in the sprint, the story points, the movement signals, the open blockers, the previous sprint's baseline, and a capacity projection. The baseline's delivered points are measured at the previous sprint's end date, so work closed later is not credited to it. Every item in `Review` also carries the pull requests Jira links to it, because that is where the reader's next click goes. It returns the report in one document. 3. **Do not recompute by hand, and do not re-query Jira.** These four queries look right and return wrong answers: - `status = Done`, `status = 'To Do'`, `priority = Highest`, `priority = High` match nothing in HYPERFLEET, which uses `Backlog` / `In Progress` / `Review` / `Closed` and `Major` / `Normal`. Use status categories, which the script does. @@ -42,10 +42,11 @@ Comprehensive sprint health report for team leads and scrum masters. 4. **Reproduce the script's output.** Present its sections as given: Sprint Overview, Progress by status, Risk assessment, Carry-over, Capacity, Team workload. Keep the numbers verbatim, including the ones that look wrong; if a number is wrong, fix the script, not the text. - Three definitions matter when you read it: + Four definitions matter when you read it: - **Progress** is shown twice, by story points and by item count. The bar and the headline percentage use story points. Say which one you are quoting. - **Movement** is the most recent of the exact last status change, the last human comment and the assignment to the current owner. The status and assignment parts need `JIRA_API_TOKEN`; without it the report falls back to `statusCategoryChangedDate` and comments only, so an item can look older than it is. A failed or unavailable changelog read adds a `signal: partial` line to the Method section; keep that line in the report. - **Capacity** is a projection from the previous sprint's pace, not a commitment. At the start of a sprint it is mostly noise; from mid-sprint on it is the number to argue with. + - **Pull requests** appear only on items in `Review`, read from the links the team attached in Jira. A failed read adds its own `signal: partial` line; keep it. A listed pull request may already be merged - the link says "there is something to review", not "it is still pending". 5. **Add Recommendations.** The script cannot write these: they need a decision. - Each recommendation names who decides and a due date. A follow-up with no name and no date is not a follow-up. @@ -76,6 +77,8 @@ Match the syntax to the destination, because only one of the three renders all o Links are the default, not a decoration. When the destination cannot render them, say so in the reply and switch the whole report to `--link-style bare`; never strip the links from part of the report. +An item in `Review` also carries its pull requests at the end of the line, as `- PR [#177](url)`. Jira's development panel is the source, so the link is whatever the team already attached to the ticket: a branch or a commit is not shown, because it is not what the reviewer opens. The panel carries the link and not the state, so a pull request listed here may already be merged - the link says "there is something to review", never "it is still pending". When the lookup fails, the Method section says so in its own `signal: partial` line instead of silently dropping the link. + ## Output Format The script's `--format markdown` output **is** the report: present it as Markdown, then add Recommendations. @@ -114,7 +117,7 @@ Progress: [=====> ] X% by SP (X of X) | X% by count (X of X) - KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - [X days without movement] #### Stale in progress/review -- KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - [X days without movement] +- KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - [X days without movement] - PR [#N](url) #### Missing data - Unestimated open items: X diff --git a/hyperfleet-jira/scripts/jira_common.py b/hyperfleet-jira/scripts/jira_common.py index 8969f8c..37ba5cc 100644 --- a/hyperfleet-jira/scripts/jira_common.py +++ b/hyperfleet-jira/scripts/jira_common.py @@ -481,6 +481,124 @@ def read_changelog( return (None, None), str(exc) +PR_URL = re.compile(r"/pull/(\d+)") + + +def pull_requests_from(payload: list) -> list[dict]: + """[(number, url)] of the pull requests in a remote-link payload. + + Jira's development panel stores a branch and a commit as remote links too, + with the same shape as a pull request, so the URL decides: only `/pull/` + counts. Duplicates are common (a PR appears once per branch event), so the + number dedupes them. + + Order is newest first, by number: within one repository the number grows, so + the highest one is the latest attempt at the ticket. + """ + found: dict[int, str] = {} + for link in payload or []: + if not isinstance(link, dict): + continue + url = ((link.get("object") or {}).get("url") or "").strip() + match = PR_URL.search(url) + if not match or not url.startswith("https://"): + continue + found.setdefault(int(match.group(1)), url) + return [{"number": number, "url": found[number]} for number in sorted(found, reverse=True)] + + +def read_pull_requests( + key: str, api: tuple[str, str] | None +) -> tuple[list[dict], str | None]: + """(pull requests Jira links to the issue, error). + + The panel shows the link, not the state: an open and a merged pull request + look the same here, so this says "there is something to review", never "it is + still under review". + """ + if not api: + return [], "no JIRA_API_TOKEN or jira-cli login" + server, auth = api + request = urllib.request.Request( + f"{server}/rest/api/3/issue/{key}/remotelink", + headers={"Authorization": f"Basic {auth}", "Accept": "application/json"}, + ) + try: + with open_changelog(request) as response: + payload = json.load(response) + except ( + urllib.error.URLError, + http.client.HTTPException, + OSError, + ValueError, + ) as exc: + return [], f"{key}: {type(exc).__name__}" + return pull_requests_from(payload), None + + +def apply_pull_requests(items: list[dict], jobs: int) -> dict: + """Attach `pr` to the items in review; every other item gets an empty list. + + A pull request exists only once work has something to show, so the lookup is + scoped to `Review`: it is the one status where the reader's next click is the + pull request rather than the ticket. + """ + for item in items: + item["pr"] = [] + + in_review = [item for item in items if item.get("status") == "Review"] + if not in_review: + return {"available": True, "failed": 0, "checked": 0, "found": 0} + + api = jira_api() + if not api: + return { + "available": False, + "failed": 0, + "checked": len(in_review), + "found": 0, + "reason": "no JIRA_API_TOKEN or jira-cli login", + } + + with ThreadPoolExecutor(max_workers=jobs) as pool: + results = list(pool.map(lambda item: read_pull_requests(item["key"], api), in_review)) + + failed = found = 0 + for item, (prs, error) in zip(in_review, results): + if error: + failed += 1 + if prs: + found += 1 + item["pr"] = prs + + return { + "available": failed == 0, + "failed": failed, + "checked": len(in_review), + "found": found, + } + + +def pr_ref(pr: dict, style: str) -> str: + """A pull request rendered for the destination, like `ticket_ref`.""" + number, url = pr["number"], pr["url"] + if style == "bare": + return f"#{number} ({url})" + if style == "slack": + return f"<{url}|#{number}>" + return f"[#{number}]({url})" + + +def pr_refs(item: dict, style: str, limit: int = 2) -> str: + """`PR #1, #2 +1` for an item, or "" when Jira links no pull request.""" + prs = item.get("pr") or [] + if not prs: + return "" + shown = ", ".join(pr_ref(pr, style) for pr in prs[:limit]) + more = f" +{len(prs) - limit}" if len(prs) > limit else "" + return f"PR {shown}{more}" + + def apply_changelog_signals(items: list[dict], today: date, jobs: int) -> dict: """Reset the movement clock on an exact status change or a new owner. diff --git a/hyperfleet-jira/scripts/pulse_check.py b/hyperfleet-jira/scripts/pulse_check.py index b4c305e..27c840c 100755 --- a/hyperfleet-jira/scripts/pulse_check.py +++ b/hyperfleet-jira/scripts/pulse_check.py @@ -40,11 +40,13 @@ JiraError, active_sprint, apply_changelog_signals, + apply_pull_requests, describe, fetch_all, jira_base_url, open_links, parse_date, + pr_refs, project_key, run_jira, status_category, @@ -204,6 +206,12 @@ def build(args) -> dict: def ref(key: str) -> str: return ticket_ref(key, base_url, args.link_style) + pr_signal = ( + apply_pull_requests(items, args.jobs) + if not args.no_prs + else {"available": True, "failed": 0, "checked": 0, "found": 0, "skipped": True} + ) + for item in items: item["open_blockers"] = open_links(item["blocked_by"], category_of) item["blocked"] = bool(item["open_blockers"]) @@ -218,6 +226,15 @@ def ref(key: str) -> str: ] item["blocks_open"] = open_links(item["blocks"], category_of) item["ask"] = suggested_ask(item, ref) + prs = pr_refs(item, args.link_style) + if prs: + # The pull request is where a reviewer acts, so it rides in the ask + # rather than in a seventh column. The generic review ask names no + # ticket, so the PR becomes its object instead of a suffix. + if item["ask"].startswith("Ask a reviewer"): + item["ask"] = f"{item['ask']} {prs}" + else: + item["ask"] = f"{item['ask']} - {prs}" owned = [i for i in items if i["owner"]] unowned = [i for i in items if not i["owner"]] @@ -255,6 +272,7 @@ def ref(key: str) -> str: "because bulk edits inflate it" ), "changelog_signal": signals, + "pr_signal": pr_signal, "totals": { "items": len(items), "sp": sum(i["sp"] for i in items), @@ -381,6 +399,17 @@ def ref(key: str) -> str: "Signal: partial - no JIRA_API_TOKEN, so movement ignores exact status " "changes and assignments" ) + prs = data.get("pr_signal") or {} + if prs.get("failed"): + lines.append( + f"Signal: partial - {prs['failed']} of {prs['checked']} pull request reads " + "failed, so those items carry no pull request link" + ) + elif prs.get("available") is False and not prs.get("skipped"): + lines.append( + "Signal: partial - pull request links unavailable " + f"({prs.get('reason') or 'no JIRA_API_TOKEN'})" + ) lines.append(data["definition"]) lines.append(f"Next pulse: {data['next_pulse'] or 'to be scheduled'}") return "\n".join(lines) @@ -403,6 +432,11 @@ def main() -> int: parser.add_argument("--sp-field", default="customfield_10028", help="custom field id holding story points") parser.add_argument("--sp-field-name", default="Story Points", type=field_name, help="JQL name of the story points field") parser.add_argument("--today", help="YYYY-MM-DD, for reproducible runs") + parser.add_argument( + "--no-prs", + action="store_true", + help="skip the pull request lookup for items in review", + ) parser.add_argument("--next-pulse", help="YYYY-MM-DD printed in the text output") parser.add_argument( "--link-style", diff --git a/hyperfleet-jira/scripts/sprint_status.py b/hyperfleet-jira/scripts/sprint_status.py index 10631f5..1232b0a 100755 --- a/hyperfleet-jira/scripts/sprint_status.py +++ b/hyperfleet-jira/scripts/sprint_status.py @@ -46,12 +46,14 @@ JiraError, active_sprint, apply_changelog_signals, + apply_pull_requests, describe, fetch_all, jira_base_url, jql_project, open_links, parse_date, + pr_refs, project_key, search_keys, sprint_rows, @@ -398,6 +400,11 @@ def build(args) -> dict: totals = summarise(items) open_items = [item for item in items if not item["is_done"]] + pr_signal = ( + apply_pull_requests(open_items, args.jobs) + if not args.no_prs + else {"available": True, "failed": 0, "checked": 0, "found": 0, "skipped": True} + ) open_statuses = [ bucket["status"] for bucket in totals["by_status"] if bucket["category"] != "Done" ] @@ -491,6 +498,7 @@ def build(args) -> dict: "baseline": baseline, "capacity": projection, "changelog_signal": signals, + "pr_signal": pr_signal, "notes": { "progress_basis": "percent_by_sp is closed story points over total story points", "movement_basis": ( @@ -525,6 +533,10 @@ def render_text(data: dict) -> str: def ref(key: str) -> str: return ticket_ref(key, base_url, style) + def pr_tail(item: dict) -> str: + rendered = pr_refs(item, style) + return f" - {rendered}" if rendered else "" + lines: list[str] = [] lines.append(f"Sprint: {sprint['name']}") @@ -593,7 +605,7 @@ def ref(key: str) -> str: owner = item["owner"] or "UNASSIGNED" lines.append( f"- {ref(item['key'])}: {item['summary']} - {owner} - {item['status']} - " - f"blocked by {detail}" + f"blocked by {detail}{pr_tail(item)}" ) if blockers["blocked_items"] > 10: lines.append(f"+{blockers['blocked_items'] - 10} more blocked items") @@ -609,7 +621,7 @@ def ref(key: str) -> str: owner = item["owner"] or "UNASSIGNED" lines.append( f"- {ref(item['key'])}: {item['summary']} - {owner} - {item['status']} " - f"({item['days_without_movement']}d without movement)" + f"({item['days_without_movement']}d without movement){pr_tail(item)}" ) else: seen = ", ".join(blockers["priorities_seen"]) or "none recorded" @@ -627,7 +639,7 @@ def ref(key: str) -> str: owner = item["owner"] or "UNASSIGNED" lines.append( f"- {ref(item['key'])}: {item['summary']} - {owner} - {item['status']} " - f"({item['days_without_movement']}d)" + f"({item['days_without_movement']}d){pr_tail(item)}" ) if at_risk["stale_items"] > 5: lines.append(f"+{at_risk['stale_items'] - 5} more stale items") @@ -689,6 +701,17 @@ def ref(key: str) -> str: "- signal: partial - no JIRA_API_TOKEN, so movement ignores exact status " "changes and assignments" ) + prs = data.get("pr_signal") or {} + if prs.get("failed"): + lines.append( + f"- signal: partial - {prs['failed']} of {prs['checked']} pull request reads " + "failed, so those items carry no pull request link" + ) + elif prs.get("available") is False and not prs.get("skipped"): + lines.append( + "- signal: partial - pull request links unavailable (" + f"{prs.get('reason') or 'no JIRA_API_TOKEN'})" + ) return "\n".join(lines) @@ -702,6 +725,11 @@ def main() -> int: parser.add_argument("--stale-days", type=int, default=5, help="days without movement that count as stale") parser.add_argument("--today", help="YYYY-MM-DD, for reproducible runs") parser.add_argument("--no-baseline", action="store_true", help="skip the previous sprint lookup") + parser.add_argument( + "--no-prs", + action="store_true", + help="skip the pull request lookup for items in review", + ) parser.add_argument("--jobs", type=int, default=8) parser.add_argument( "--link-style", diff --git a/hyperfleet-jira/tests/test_pulse_check.py b/hyperfleet-jira/tests/test_pulse_check.py index 6e317cc..3b5181d 100644 --- a/hyperfleet-jira/tests/test_pulse_check.py +++ b/hyperfleet-jira/tests/test_pulse_check.py @@ -651,6 +651,14 @@ def test_bare_style_leaves_every_key_plain(self): self.assertIn("Escalation 20+ days: HYPERFLEET-2", text) self.assertNotIn("](", text) + def test_a_failed_pull_request_read_is_named(self): + data = self.data() + data["pr_signal"] = {"available": False, "failed": 1, "checked": 3, "found": 0} + self.assertIn( + "Signal: partial - 1 of 3 pull request reads failed", + pc.render_text(data), + ) + def test_a_failed_changelog_read_is_named_in_the_report(self): data = self.data() data["changelog_signal"] = { diff --git a/hyperfleet-jira/tests/test_sprint_status.py b/hyperfleet-jira/tests/test_sprint_status.py index 3e28969..9bdf0a0 100644 --- a/hyperfleet-jira/tests/test_sprint_status.py +++ b/hyperfleet-jira/tests/test_sprint_status.py @@ -344,6 +344,74 @@ def test_no_base_url_falls_back_to_bare(self): self.assertEqual(ss.ticket_ref("HYPERFLEET-1", None, "markdown"), "HYPERFLEET-1") +class PullRequestTest(unittest.TestCase): + """The development panel lists branches and commits beside pull requests.""" + + pr = {"number": 104, "url": "https://github.com/o/r/pull/104"} + + def payload(self): + return [ + {"object": {"url": "https://github.com/o/r/pull/104"}}, + {"object": {"url": "https://github.com/o/r/pull/104"}}, + {"object": {"url": "https://github.com/o/r/tree/pr-links"}}, + {"object": {"url": "https://github.com/o/r/commit/abc123"}}, + {"object": {"url": "https://github.com/o/r/pull/99"}}, + {"object": {"url": "http://github.com/o/r/pull/7"}}, + ] + + def test_only_pull_request_urls_count_and_a_duplicate_is_listed_once(self): + prs = jc.pull_requests_from(self.payload()) + self.assertEqual([pr["number"] for pr in prs], [104, 99]) + + def test_the_newest_pull_request_comes_first(self): + prs = jc.pull_requests_from( + [ + {"object": {"url": "https://github.com/o/r/pull/9"}}, + {"object": {"url": "https://github.com/o/r/pull/120"}}, + {"object": {"url": "https://github.com/o/r/pull/11"}}, + ] + ) + self.assertEqual([pr["number"] for pr in prs], [120, 11, 9]) + + def test_markdown_links_the_number_not_the_url(self): + self.assertEqual( + jc.pr_ref(self.pr, "markdown"), + "[#104](https://github.com/o/r/pull/104)", + ) + + def test_slack_wraps_the_url_with_the_number_as_text(self): + self.assertEqual( + jc.pr_ref(self.pr, "slack"), + "", + ) + + def test_bare_style_keeps_the_url_the_reader_would_lose(self): + self.assertIn("https://github.com/o/r/pull/104", jc.pr_ref(self.pr, "bare")) + + def test_pr_refs_caps_the_list_and_counts_the_rest(self): + item = { + "pr": [ + {"number": number, "url": f"https://github.com/o/r/pull/{number}"} + for number in (3, 2, 1) + ] + } + self.assertTrue(jc.pr_refs(item, "markdown").endswith("+1")) + + def test_an_item_without_a_pull_request_renders_nothing(self): + self.assertEqual(jc.pr_refs({"pr": []}, "markdown"), "") + + def test_only_review_items_are_looked_up(self): + items = [ + {"key": "HYPERFLEET-1", "status": "Review"}, + {"key": "HYPERFLEET-2", "status": "Backlog"}, + ] + with mock.patch.object(jc, "jira_api", return_value=None): + signal = jc.apply_pull_requests(items, 2) + self.assertEqual(signal["checked"], 1) + self.assertFalse(signal["available"]) + self.assertEqual(items[1]["pr"], []) + + class PreviousSprintTest(unittest.TestCase): rows = [ {"id": "1", "name": "Sprint 17", "start": "2026-09-01", "end": "2026-09-21", "state": "closed"}, @@ -420,6 +488,32 @@ def test_method_names_all_three_bases(self): for basis in ("movement basis", "progress basis", "baseline basis"): self.assertIn(basis, text) + def test_a_review_item_carries_its_pull_request(self): + data = self.data() + data["jira_base_url"] = "https://example.atlassian.net/browse/" + data["link_style"] = "markdown" + data["at_risk"]["stale"] = [ + { + "key": "HYPERFLEET-9", + "summary": "An item", + "owner": "A Person", + "status": "Review", + "days_without_movement": 7, + "pr": [{"number": 104, "url": "https://github.com/o/r/pull/104"}], + } + ] + data["at_risk"]["stale_items"] = 1 + self.assertIn( + "(7d) - PR [#104](https://github.com/o/r/pull/104)", ss.render_text(data) + ) + + def test_a_failed_pull_request_read_is_named(self): + data = self.data() + data["pr_signal"] = {"available": False, "failed": 2, "checked": 5, "found": 1} + self.assertIn( + "signal: partial - 2 of 5 pull request reads failed", ss.render_text(data) + ) + def test_a_failed_changelog_read_is_named_in_the_report(self): data = self.data() data["changelog_signal"] = {"available": False, "failed": 2, "checked": 7} From 03b0dbb51cd6d602eee915e331c64949aecb6c65 Mon Sep 17 00:00:00 2001 From: Rafael Benevides Date: Tue, 3 Nov 2026 15:26:47 -0300 Subject: [PATCH 9/9] HYPERFLEET-1890 - fix(hyperfleet-jira): take pull request ownership from the title Jira links a pull request to every ticket its title mentions, so the link on its own does not say whose pull request it is. HYPERFLEET-1669 carried `architecture#255`, titled HYPERFLEET-1636, and the sprint report told the lead to review one PR as the blocker of two unrelated stalls - and to treat it as the shared prerequisite of a chain it does not own. HYPERFLEET-1709 carried the same noise: `architecture#218` is titled HYPERFLEET-1670. Only a pull request whose title names the ticket now counts, matched on the key with a digit boundary so HYPERFLEET-1636 does not match HYPERFLEET-16360. A title with no key at all is dropped as well: an unverified link reads as ownership. A pull request that names both tickets still lands on both. Covered by four tests: another ticket's PR, a PR naming both tickets, a title with no key, and the longer-key prefix. --- .../commands/sprint-pulse-check.md | 2 +- hyperfleet-jira/commands/sprint-status.md | 8 +- hyperfleet-jira/scripts/jira_common.py | 37 ++++++---- hyperfleet-jira/tests/test_sprint_status.py | 74 +++++++++++++++---- 4 files changed, 92 insertions(+), 29 deletions(-) diff --git a/hyperfleet-jira/commands/sprint-pulse-check.md b/hyperfleet-jira/commands/sprint-pulse-check.md index 7a117fc..2057273 100644 --- a/hyperfleet-jira/commands/sprint-pulse-check.md +++ b/hyperfleet-jira/commands/sprint-pulse-check.md @@ -98,7 +98,7 @@ Rules for the output: - **Never wrap the report in a code fence for chat or TUI.** The fence in the template is illustrative: inside it the links and emphasis reach the reader as literal characters. Use the fence only when the destination is Slack, email, or a log file, and say which one you are formatting for. - **Print the base URL once, under the title.** It documents where the links point; it is not a fallback for unlinked keys. The script emits it from the `server:` entry in `~/.config/.jira/.config.yml`; never hardcode it. - **Every ticket key is a link**, in the table and in the prose lines below it (`No action`, `Escalation`, `assign these first`). `--format text` prints them already rendered; this command reads `--format json`, where the key stays bare and the payload carries `jira_base_url` and `link_style` instead, so render each key yourself: `[HYPERFLEET-XXXX](HYPERFLEET-XXXX)` for chat or TUI, `` for `--link-style slack`, the bare key for `--link-style bare`. Never mix two styles in one output. Do not re-render text that already arrives rendered - the `Ask` string is composed by the script and comes with its keys in the chosen style. -- **A pull request is a link too.** For an item in `Review` the script appends the pull requests Jira links to the ticket: `Ask a reviewer to approve or reject PR [#177](url)` when the ask is generic, `- PR [#177](url)` after a named blocker. It rides in the `Ask`, already rendered in the chosen style, and is not a seventh column - `Ask` is where the reviewer acts. The development panel carries the link and not the state, so the PR may already be merged; and a branch or a commit is not shown, because it is not what a reviewer opens. If the lookup fails, the signal line below the queue says so. +- **A pull request is a link too.** For an item in `Review` the script appends the pull requests Jira links to the ticket: `Ask a reviewer to approve or reject PR [#177](url)` when the ask is generic, `- PR [#177](url)` after a named blocker. It rides in the `Ask`, already rendered in the chosen style, and is not a seventh column - `Ask` is where the reviewer acts. Only a pull request whose **title** names the ticket counts: Jira links the same pull request to every ticket it mentions, so the link alone is not ownership and a cross-reference is dropped. A branch or a commit is not shown, because it is not what a reviewer opens; the panel carries the link and not the state, so the PR may already be merged. If the lookup fails, the signal line below the queue says so. - **One table row per item, six columns, `Ask` last.** `Ticket | Title | Owner | SP | Status · age | Ask`. No second row, no empty cell: an `Ask` row under the data row squeezes the text into the first column, and Markdown has no `colspan` to fix it. `Ask` sits last because the last column is the one that grows, so a long ask wraps at the right edge instead of widening the table from the left. - **Status and age share a column.** "Review · 12d" is one thought for the reader. Splitting it into two columns costs width and buys nothing. - **Keep the title and the SP.** Without the title the ask loses its referent; without the SP an 8-point item gets the same nudge as a 5. diff --git a/hyperfleet-jira/commands/sprint-status.md b/hyperfleet-jira/commands/sprint-status.md index 5ddcb27..8d03ee7 100644 --- a/hyperfleet-jira/commands/sprint-status.md +++ b/hyperfleet-jira/commands/sprint-status.md @@ -46,7 +46,7 @@ Comprehensive sprint health report for team leads and scrum masters. - **Progress** is shown twice, by story points and by item count. The bar and the headline percentage use story points. Say which one you are quoting. - **Movement** is the most recent of the exact last status change, the last human comment and the assignment to the current owner. The status and assignment parts need `JIRA_API_TOKEN`; without it the report falls back to `statusCategoryChangedDate` and comments only, so an item can look older than it is. A failed or unavailable changelog read adds a `signal: partial` line to the Method section; keep that line in the report. - **Capacity** is a projection from the previous sprint's pace, not a commitment. At the start of a sprint it is mostly noise; from mid-sprint on it is the number to argue with. - - **Pull requests** appear only on items in `Review`, read from the links the team attached in Jira. A failed read adds its own `signal: partial` line; keep it. A listed pull request may already be merged - the link says "there is something to review", not "it is still pending". + - **Pull requests** appear only on items in `Review`, read from the links the team attached in Jira. Only a pull request whose title names the ticket counts: Jira links the same pull request to every ticket it mentions, so the link alone is not ownership, and a "stale in review" item can point at someone else's diff. A failed read adds its own `signal: partial` line; keep it. A listed pull request may already be merged - the link says "there is something to review", not "it is still pending". 5. **Add Recommendations.** The script cannot write these: they need a decision. - Each recommendation names who decides and a due date. A follow-up with no name and no date is not a follow-up. @@ -77,7 +77,11 @@ Match the syntax to the destination, because only one of the three renders all o Links are the default, not a decoration. When the destination cannot render them, say so in the reply and switch the whole report to `--link-style bare`; never strip the links from part of the report. -An item in `Review` also carries its pull requests at the end of the line, as `- PR [#177](url)`. Jira's development panel is the source, so the link is whatever the team already attached to the ticket: a branch or a commit is not shown, because it is not what the reviewer opens. The panel carries the link and not the state, so a pull request listed here may already be merged - the link says "there is something to review", never "it is still pending". When the lookup fails, the Method section says so in its own `signal: partial` line instead of silently dropping the link. +An item in `Review` also carries its pull requests at the end of the line, as `- PR [#177](url)`. Jira's development panel is the source, so the link is whatever the team already attached to the ticket: a branch or a commit is not shown, because it is not what the reviewer opens. + +The pull request's **title** decides ownership, not the link. Jira links a pull request to every ticket its title mentions, so a link whose title names another ticket is a cross-reference: reporting it as this ticket's pull request sends the reviewer to the wrong diff, and it makes two stalls look like one shared blocker. A title with no ticket key at all is dropped for the same reason - an unverified link reads as ownership. + +The panel carries the link and not the state, so a pull request listed here may already be merged - the link says "there is something to review", never "it is still pending". When the lookup fails, the Method section says so in its own `signal: partial` line instead of silently dropping the link. ## Output Format diff --git a/hyperfleet-jira/scripts/jira_common.py b/hyperfleet-jira/scripts/jira_common.py index 37ba5cc..d7b7474 100644 --- a/hyperfleet-jira/scripts/jira_common.py +++ b/hyperfleet-jira/scripts/jira_common.py @@ -484,25 +484,35 @@ def read_changelog( PR_URL = re.compile(r"/pull/(\d+)") -def pull_requests_from(payload: list) -> list[dict]: - """[(number, url)] of the pull requests in a remote-link payload. - - Jira's development panel stores a branch and a commit as remote links too, - with the same shape as a pull request, so the URL decides: only `/pull/` - counts. Duplicates are common (a PR appears once per branch event), so the - number dedupes them. - - Order is newest first, by number: within one repository the number grows, so - the highest one is the latest attempt at the ticket. +def pull_requests_from(payload: list, key: str) -> list[dict]: + """[(number, url)] of the pull requests that belong to `key`. + + Two filters, because the panel is generous: + + - The URL must be a pull request. Jira stores a branch and a commit as remote + links too, in the same shape, so only `/pull/` counts. + - The title must name `key`. Jira links a pull request to every ticket its + title mentions, so a link on HYPERFLEET-1669 can be the pull request of + HYPERFLEET-1636; reporting that as 1669's pull request sends the reviewer to + the wrong diff. A title with no key at all is dropped as well: an + unverified link reads as ownership. + + Duplicates are common (a PR appears once per branch event), so the number + dedupes them. Order is newest first: within one repository the number grows, + so the highest one is the latest attempt at the ticket. """ + wanted = re.compile(rf"{re.escape(key)}(?!\d)", re.IGNORECASE) found: dict[int, str] = {} for link in payload or []: if not isinstance(link, dict): continue - url = ((link.get("object") or {}).get("url") or "").strip() + obj = link.get("object") or {} + url = (obj.get("url") or "").strip() match = PR_URL.search(url) if not match or not url.startswith("https://"): continue + if not wanted.search(obj.get("title") or ""): + continue found.setdefault(int(match.group(1)), url) return [{"number": number, "url": found[number]} for number in sorted(found, reverse=True)] @@ -514,7 +524,8 @@ def read_pull_requests( The panel shows the link, not the state: an open and a merged pull request look the same here, so this says "there is something to review", never "it is - still under review". + still under review". Ownership comes from the title - see + `pull_requests_from`. """ if not api: return [], "no JIRA_API_TOKEN or jira-cli login" @@ -533,7 +544,7 @@ def read_pull_requests( ValueError, ) as exc: return [], f"{key}: {type(exc).__name__}" - return pull_requests_from(payload), None + return pull_requests_from(payload, key), None def apply_pull_requests(items: list[dict], jobs: int) -> dict: diff --git a/hyperfleet-jira/tests/test_sprint_status.py b/hyperfleet-jira/tests/test_sprint_status.py index 9bdf0a0..8cffc00 100644 --- a/hyperfleet-jira/tests/test_sprint_status.py +++ b/hyperfleet-jira/tests/test_sprint_status.py @@ -345,31 +345,79 @@ def test_no_base_url_falls_back_to_bare(self): class PullRequestTest(unittest.TestCase): - """The development panel lists branches and commits beside pull requests.""" + """The development panel lists branches, commits and other tickets' pull requests.""" pr = {"number": 104, "url": "https://github.com/o/r/pull/104"} - def payload(self): + def payload(self, key="HYPERFLEET-104"): return [ - {"object": {"url": "https://github.com/o/r/pull/104"}}, - {"object": {"url": "https://github.com/o/r/pull/104"}}, - {"object": {"url": "https://github.com/o/r/tree/pr-links"}}, - {"object": {"url": "https://github.com/o/r/commit/abc123"}}, - {"object": {"url": "https://github.com/o/r/pull/99"}}, - {"object": {"url": "http://github.com/o/r/pull/7"}}, + {"object": {"url": "https://github.com/o/r/pull/104", + "title": f"{key} - fix: a thing"}}, + {"object": {"url": "https://github.com/o/r/pull/104", + "title": f"{key} - fix: a thing"}}, + {"object": {"url": "https://github.com/o/r/tree/pr-links", "title": key}}, + {"object": {"url": "https://github.com/o/r/commit/abc123", "title": key}}, + {"object": {"url": "https://github.com/o/r/pull/99", "title": f"{key} - fix: older"}}, + {"object": {"url": "http://github.com/o/r/pull/7", "title": f"{key} - fix: cleartext"}}, ] def test_only_pull_request_urls_count_and_a_duplicate_is_listed_once(self): - prs = jc.pull_requests_from(self.payload()) + prs = jc.pull_requests_from(self.payload(), "HYPERFLEET-104") self.assertEqual([pr["number"] for pr in prs], [104, 99]) + def test_a_pull_request_titled_for_another_ticket_is_not_this_tickets(self): + payload = [ + { + "object": { + "url": "https://github.com/o/r/pull/255", + "title": "HYPERFLEET-1636 - docs: sync the wristband contract", + } + } + ] + self.assertEqual(jc.pull_requests_from(payload, "HYPERFLEET-1669"), []) + + def test_a_pull_request_that_names_both_tickets_belongs_to_both(self): + payload = [ + { + "object": { + "url": "https://github.com/o/r/pull/255", + "title": "HYPERFLEET-1636 + HYPERFLEET-1669 - docs: the contract", + } + } + ] + self.assertEqual( + [pr["number"] for pr in jc.pull_requests_from(payload, "HYPERFLEET-1669")], + [255], + ) + + def test_a_title_without_any_ticket_key_is_not_evidence(self): + payload = [ + {"object": {"url": "https://github.com/o/r/pull/5", "title": "fix: a thing"}} + ] + self.assertEqual(jc.pull_requests_from(payload, "HYPERFLEET-104"), []) + + def test_a_longer_key_does_not_match_the_shorter_one(self): + payload = [ + { + "object": { + "url": "https://github.com/o/r/pull/6", + "title": "HYPERFLEET-16360 - fix: a thing", + } + } + ] + self.assertEqual(jc.pull_requests_from(payload, "HYPERFLEET-1636"), []) + def test_the_newest_pull_request_comes_first(self): prs = jc.pull_requests_from( [ - {"object": {"url": "https://github.com/o/r/pull/9"}}, - {"object": {"url": "https://github.com/o/r/pull/120"}}, - {"object": {"url": "https://github.com/o/r/pull/11"}}, - ] + {"object": {"url": "https://github.com/o/r/pull/9", + "title": "HYPERFLEET-104 - a"}}, + {"object": {"url": "https://github.com/o/r/pull/120", + "title": "HYPERFLEET-104 - b"}}, + {"object": {"url": "https://github.com/o/r/pull/11", + "title": "HYPERFLEET-104 - c"}}, + ], + "HYPERFLEET-104", ) self.assertEqual([pr["number"] for pr in prs], [120, 11, 9])