diff --git a/.github/workflows/README.md b/.github/workflows/README.md index e6a36be..c54a5d5 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -1,5 +1,26 @@ # CI Workflows +Run all discovered plugin test suites locally before opening a PR: + +```bash +make test +``` + +The Makefile exposes `help` and `test`; the aggregate test target discovers each +suite's `run-tests.sh`. See [CONTRIBUTING.md](../../CONTRIBUTING.md#testing) for +the authoritative runner contract and dependencies. +To run one suite in isolation, invoke its runner directly, for example: + +```bash +bash hyperfleet-jira/tests/run-tests.sh +``` + +The workflows in this directory cover only the scheduled work. + +The Prow unit job is configured separately in `openshift/release` under +`ci-operator/config/openshift-hyperfleet/hyperfleet-claude-plugins` and runs +`make test`. Until the presubmit is active, validation must be run locally. + ## Open PRs Digest **File:** `open-prs-digest.yml` diff --git a/AGENTS.md b/AGENTS.md index 54c5c41..ad59afe 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.1 | | `hyperfleet-architecture` | 1 | - | - | - | 0.2.0 | | `hyperfleet-standards` | 1 | - | - | - | 1.1.0 | | `hyperfleet-operational-readiness` | 1 | - | - | - | 0.2.0 | @@ -88,6 +88,13 @@ runner contract. Every new suite MUST provide the documented `run-tests.sh`; new tests in an existing suite reuse its runner. Run `make test` before opening a PR and confirm your suite appears in the log. +Rules for a change to a plugin that has a suite: + +- **Run the suite before opening the PR.** A red test is a review comment you wrote yourself. +- **A script change needs one live run.** The tests stub Jira, so they prove the branches, not the report: run the collector against a real sprint and check that two runs in a row agree. +- **A command file is a contract about script output.** A sentence in `commands/*.md` that describes what a script emits is executable prose. Change the script and the sentence in the same PR; change the sentence and read the branch it describes. This divergence has reached review twice in this repository. +- **A docs-only change still has to be true.** Confirm the command you document exists in `commands/` (a skill is not a command) and that every flag matches the script's `argparse`. + ## Boundaries **DO:** diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 332f35a..455ffc4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -110,8 +110,9 @@ the runner, not the Makefile. Python unittest runners should honor the CI build root provides them. The existing work-triage suite requires Bash, `jq`, and `bc`. -Keep only the aggregate `test` target in the root Makefile; do not add per-suite -targets or a hand-maintained suite list. To run one suite in isolation, invoke +The root Makefile provides `help`, which only lists available targets and their +descriptions, and the aggregate `test` target. Do not add per-suite targets or a +hand-maintained suite list. To run one suite in isolation, invoke its runner directly: ```bash diff --git a/Makefile b/Makefile index 195485a..32023ac 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,10 @@ -.PHONY: test +.PHONY: help test + +help: ## Show available targets without running them + @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z_-]+:.*## / {printf " %-12s %s\n", $$1, $$2}' $(MAKEFILE_LIST) # Shared entry point for local runs and the Prow unit job. -test: +test: ## Run all discovered test suites @found=0; \ for script in */tests/run-tests.sh */skills/*/scripts/tests/run-tests.sh; do \ [ -f "$$script" ] || continue; \ diff --git a/README.md b/README.md index 62531f8..eb8b1b1 100644 --- a/README.md +++ b/README.md @@ -47,9 +47,10 @@ Questions or feedback? Open an issue in this repository. ## Testing -Run all discovered test suites from the repository root: +List available targets and run all discovered test suites from the repository root: ```bash +make help make test ``` diff --git a/hyperfleet-jira/.claude-plugin/plugin.json b/hyperfleet-jira/.claude-plugin/plugin.json index 600b0e3..b6798ff 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.1", "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..ff651d5 100644 --- a/hyperfleet-jira/README.md +++ b/hyperfleet-jira/README.md @@ -5,14 +5,15 @@ A Claude Code plugin that integrates JIRA with your development workflow using [ ## Features ### For Engineers -- **`/my-sprint`** - View current sprint and your assigned tickets -- **`/my-tasks`** - List all your assigned tasks across projects -- **`/new-comments`** - Find tickets with comments you may have missed +- **`/hyperfleet-jira:my-sprint`** - View current sprint and your assigned tickets +- **`/hyperfleet-jira:my-tasks`** - List all your assigned tasks across projects +- **`/hyperfleet-jira:new-comments`** - Find tickets with comments you may have missed ### For Team Leads -- **`/sprint-status`** - Comprehensive sprint health overview -- **`/team-weekly-update`** - Weekly team progress report grouped by activity type and epic -- **`/triage`** - Audit tickets for missing fields and quality issues +- **`/hyperfleet-jira:sprint-status`** - Comprehensive sprint health overview +- **`/hyperfleet-jira:sprint-pulse-check`** - Twice-weekly nudge queue for large work items (5 SP and above) +- **`/hyperfleet-jira:team-weekly-update`** - Weekly team progress report grouped by activity type and epic +- **`/hyperfleet-jira:triage`** - Audit tickets for missing fields and quality issues ### Skills (Auto-Activated) - **jira-ticket-creator** - Creates well-structured tickets with What/Why/Acceptance Criteria, duplicate check, story points, activity type, component, parent epic, and validation gate @@ -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 @@ -92,10 +94,12 @@ rm -rf "jira_${VERSION#v}_linux_x86_64" "jira_${VERSION#v}_linux_x86_64.tar.gz" ### Commands -#### `/my-sprint` +Commands are namespaced by plugin: invoke them as `/hyperfleet-jira:`. The examples below spell the namespace out, because a command such as `/sprint-status` is common enough to collide with another installed plugin. + +#### `/hyperfleet-jira:my-sprint` Shows your current sprint at a glance: -``` -/my-sprint +```text +/hyperfleet-jira:my-sprint ``` Output includes: - Sprint name and days remaining @@ -103,37 +107,81 @@ Output includes: - Story points summary - Blockers or high-priority items -#### `/my-tasks` +#### `/hyperfleet-jira:my-tasks` Lists all your assigned tickets: -``` -/my-tasks +```text +/hyperfleet-jira:my-tasks ``` -#### `/new-comments` +#### `/hyperfleet-jira:new-comments` Find tickets with recent comments: -``` -/new-comments +```text +/hyperfleet-jira:new-comments ``` -#### `/sprint-status` (Team Leads) +#### `/hyperfleet-jira:sprint-status` (Team Leads) Comprehensive sprint health report: -``` -/sprint-status -/sprint-status HF # Specific project +```text +/hyperfleet-jira:sprint-status +/hyperfleet-jira: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 totals (items, story points, and reasons) and a capacity projection from the previous sprint's pace +- Every ticket key as a link, in every section, including the blocker keys inside a line +- The pull requests of the items in `Review`, read from Jira's development panel: the GitHub app's `dev-status` record for every repository, plus any link attached by hand -#### `/team-weekly-update` (Team Leads) -Weekly progress report for team updates: +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. + +Options: `--today YYYY-MM-DD` for a reproducible run, `--sprint ` for another sprint, `--stale-days`, `--blocker-priority`, `--link-style markdown|slack|bare`, `--no-baseline`, `--no-prs`. + +The collector tests use the plugin-level runner convention: + +```bash +bash hyperfleet-jira/tests/run-tests.sh +``` + +The root `make test` discovers this runner automatically. It runs Python unittest +discovery relative to the runner's directory and returns the test process's exit +status. Set `PYTHON` to select an interpreter (default: `python3`); neither a live +Jira connection nor credentials are required for these tests. + +Both collectors invoke only `jira` from your trusted `PATH`. The `--jira` option +accepts only `jira`, not arbitrary commands or executable paths. CLI failures +report a fixed command identifier and failure reason or exit status, never raw +stdout/stderr, which may contain private issue data or authentication details. + +These rules decide what the output is worth: + +- **A pull request belongs to the ticket its title names**, and only to it. Jira attaches a pull request to every ticket its title mentions, so `architecture#255`, titled `HYPERFLEET-1636`, is `HYPERFLEET-1636`'s pull request and never `HYPERFLEET-1669`'s, even when the panel shows it on both. A link titled for another ticket, or for no ticket at all, is not printed on the ticket's line: the reviewer named there would open someone else's diff, and two stalls would read as one shared blocker. +- **Ownership is per pull request, by its own title.** A ticket can own several - the same work opened in two repositories, or a follow-up after a merge - and each is listed as its own. Numbers restart in every repository, so the URL identifies the pull request: `hyperfleet-api#120` and `hyperfleet-infra#120` are two. The `+N` on a long list is a width limit, not a ranking, and the report never asks anyone which one is the real work. +- **"No link" is not "no pull request".** The report reads Jira, not GitHub: an empty segment means no record in Jira, and the recommendation is about the link - attach the pull request, or move the ticket back. A lookup that was skipped, unavailable or failed leaves the ask neutral: an empty list from a read that did not answer is unknown, not none. +- **An unreadable issue stays unknown.** A sprint item, blocker or link target the token cannot see is skipped instead of aborting the report, a blocker whose target cannot be read stays open with status `?`, and the Method section says how many reads failed. +- **The state rides along when Jira reports one.** The panel has two kinds of record: the GitHub app's `dev-status` (every repository, with a state) and hand-attached remote links (no state). Both are read and deduplicated, so `PR [#181](url) (merged)` and `PR [#177](url)` stay distinguishable - one is a ticket waiting for its status, the other one waiting for a reviewer. `--no-prs` skips the lookup; a failed read is reported as a partial signal instead of a silent gap. + +#### `/hyperfleet-jira:sprint-pulse-check` (Team Leads) +Nudge queue for the large items, run a couple of times per week: +```text +/hyperfleet-jira:sprint-pulse-check +/hyperfleet-jira:sprint-pulse-check HF # Specific project ``` -/team-weekly-update # All teams in HYPERFLEET -/team-weekly-update HYPERFLEET # Specific project -/team-weekly-update HYPERFLEET 6278 # Specific team -/team-weekly-update "" 6278 # Default project with team filter +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 +- The pull request of an item in `Review`, inside the ask, under the same ownership rule as `/sprint-status` +- The reviewers the ask names, never the author: `dev-status` reports every requested reviewer, and the ask names all of them: `Ask Tirth and Rafael to approve or reject PR [#257](url)`. Naming one would decide who reviews, and naming the assignee would point at the person who wrote the diff. The author, a reviewer who already approved and Jira's `User ` placeholder are dropped; a hand-attached link with no reviewer list falls back to `Ask a reviewer` instead of guessing. + +#### `/hyperfleet-jira:team-weekly-update` (Team Leads) +Weekly progress report for team updates: +```text +/hyperfleet-jira:team-weekly-update # All teams in HYPERFLEET +/hyperfleet-jira:team-weekly-update HYPERFLEET # Specific project +/hyperfleet-jira:team-weekly-update HYPERFLEET 6278 # Specific team +/hyperfleet-jira:team-weekly-update "" 6278 # Default project with team filter ``` Output includes: - Closed issues from the last 7 days (Story, Task, Bug) @@ -142,11 +190,11 @@ Output includes: - Epic status tracking - Issues without parent epics highlighted -#### `/triage` (Team Leads) +#### `/hyperfleet-jira:triage` (Team Leads) Audit tickets for quality: -``` -/triage -/triage backlog # Check backlog instead of sprint +```text +/hyperfleet-jira:triage +/hyperfleet-jira:triage backlog # Check backlog instead of sprint ``` Checks for: - Missing story points @@ -191,12 +239,11 @@ The estimator analyzes: - Team velocity patterns #### Ticket Implementation Validation -Check if a ticket's requirements are implemented: -``` -/is-ticket-implemented HYPERFLEET-123 # local codebase -/is-ticket-implemented HYPERFLEET-123 github # remote (infers repo from ticket) +A skill, so it is triggered by asking rather than by a slash command: +```text +Is HYPERFLEET-123 implemented? +Is HYPERFLEET-123 implemented in the remote repo? # infers the repo from the ticket ``` -Or ask naturally: "Is HYPERFLEET-123 implemented?" / "Check if this ticket is done" Generates an acceptance report with: - Completion percentage diff --git a/hyperfleet-jira/commands/sprint-pulse-check.md b/hyperfleet-jira/commands/sprint-pulse-check.md new file mode 100644 index 0000000..88a2dc1 --- /dev/null +++ b/hyperfleet-jira/commands/sprint-pulse-check.md @@ -0,0 +1,125 @@ +--- +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 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 `/hyperfleet-jira: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/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.** 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 + python3 "$PULSE" --project HYPERFLEET --format json + ``` + Options: `--today YYYY-MM-DD` for a reproducible run, `--format markdown` 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, 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. + +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 - a reviewer the panel does not list, a blocker that just closed, a decision that stalled. Keep it to one line. + +5. **Apply the courtesies the script cannot:** + - 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. The script already names every reviewer Jira reports; rewrite it only when the panel reports none and the lead knows who was asked + - 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 person who can move the blocker - its reviewers when it is in `Review`, its owner when it is still in progress - or at assigning it 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. Every ticket key is a link. 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 | 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](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](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) + +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 +``` + +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 markdown` prints them already rendered (`text` is an alias for it); 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 whose **title** names the ticket: Jira links a pull request to every ticket its title mentions, so `architecture#255`, titled `HYPERFLEET-1636`, is never `HYPERFLEET-1669`'s. Numbers restart in every repository, so a pull request is identified by its URL: `hyperfleet-api#120` and `hyperfleet-infra#120` can both belong to the ticket. A ticket can own several; the `Ask` shows the two that fit and appends `+N`, a width limit rather than a ranking, and it never picks one or asks which is the duplicate. It rides in the `Ask`, already rendered in the chosen style, and is not a seventh column. **Name every requested reviewer, never one and never the author:** picking one would decide who reviews, and the author wrote the diff. The panel reports a state when it has one, so `(merged)` becomes `Move this ticket out of Review: PR [#181](url) (merged)`; a hand-attached link has none. With no link of its own the ask is `Attach this ticket's pull request, or move it back to In Progress` - but only when the lookup answered: a skipped (`--no-prs`), unavailable or failed read leaves the ask neutral, because an empty list then means "unread", not "none". +- **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 Tirth and Rafael 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`, `attach` (the ticket's pull request), `move` (a ticket out of `Review`), `post`, `start`, `propose` (a split), `confirm` (a date, or an unread ticket's status and owner). 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 keeps that date ask until it reaches the 20-day rung, where it asks for the decision note instead of 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 all of its requested reviewers (`Ask Tirth and Rafael to approve or reject [HYPERFLEET-1636](url) (Review 7d)`); its owner is the author, so the owner is named only when Jira reports no pull request for it. When every pull request it owns is merged or declined there is nothing left to review, so the ask becomes the queue's move instead: `move [HYPERFLEET-1636](url) out of Review: PR [#181](url) (merged)`. An unowned blocker becomes `assign [HYPERFLEET-1523](url)`, because there is nobody to ask - but only when its state was read. A blocker whose read failed - no permission, a deleted issue, a dropped connection - becomes `confirm [HYPERFLEET-1825](url)'s status and owner`: `assign` would order work that may already have an owner, and the status `?` is the only thing known about it. +- **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`. Only when `failed` is zero and `changelog_signal.available` is false, add: `Signal: partial - no JIRA_API_TOKEN, so movement ignores exact status changes and assignments`. The two are exclusive, and the order matters: a failed read also sets `available` to false, so testing `available` first would blame the missing token for a network error. The same pair applies to `pr_signal`: a non-zero `failed` adds `Signal: partial - N of M pull request reads failed; those items carry no pull request link`, and an unavailable lookup with no failures adds the reason instead. A non-zero `fetch_signal.failed` adds `Signal: partial - N issue reads failed, so those items are missing from the queue and their links stay open`; the script's `render_text` prints all three in that order. +- 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 + +Six 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 owner wrote the diff. +- **A reviewer list comes from the panel, and the panel is incomplete.** Jira reports the reviewers the GitHub app collected, and it shows `User ` for an account it can no longer resolve - the script drops those. A pull request attached by hand carries no reviewers at all, so the ask falls back to `Ask a reviewer` instead of guessing a name. +- **The queue is sprint-scoped.** A large item outside the sprint never appears, however stalled it is; that is `/hyperfleet-jira: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..61371e9 100644 --- a/hyperfleet-jira/commands/sprint-status.md +++ b/hyperfleet-jira/commands/sprint-status.md @@ -13,82 +13,150 @@ 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/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.** 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 - 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, `--no-prs` to skip the pull request 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. The baseline's delivered points are measured at the instant the previous sprint actually closed, so work closed after it - even later on the same day - is not credited to that sprint, while work closed while the sprint ran past its plan still is. The cutoff is the `completeDate` Jira recorded for that sprint; the planned end, read as the end of its day, is used only when no issue in the sprint records a `completeDate`. 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. -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 - ``` + Five 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 Jira's development panel. 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. Two repositories can both have a pull request with the same number, so the URL, not the number, identifies one. The panel reports a state when it has one - `(merged)`, `(declined)` - and a link attached by hand carries none. A failed read adds its own `signal: partial` line; keep it. + - **An unreadable issue is not a closed one.** A sprint item, blocker or link target the token cannot see is left out of the counts and its links stay open with an unknown status, and a `signal: partial` line says how many reads failed. Keep that line too. -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. A follow-up with no name is not a follow-up. + - Name the person who can say yes alone: the requested reviewer on the pull request, the assignee for a status that was never updated. The script reports those reviewers on each pull request; when it reports more than one, name all of them rather than choosing, because the choice of who reviews is theirs. When the decision belongs to a group, write the role and not its members - `decided by: Tech leads`, never a list of names. A list goes stale with the next reorganisation, and a partial list reads as the whole group. The role resolves through `OWNERS_ALIASES` in this repository; do not invent one. + - `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. + - Do not add a due date. The report has no basis for one: it does not know the reviewer's calendar, the size of the released work or the lead time of the repository. A date invented here reads as a commitment and is met by nobody, and it competes with the sprint end date, which is the only deadline the report actually knows. + - 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 SP and above), point the lead to `/hyperfleet-jira: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 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 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. +- 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: + +| 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` | + +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: the GitHub app's `dev-status` record for every repository, plus any link attached by hand, merged and deduplicated. 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 `architecture#255`, titled `HYPERFLEET-1636`, is the pull request of `HYPERFLEET-1636` and never of `HYPERFLEET-1669`, even when the panel shows it on both. The line therefore carries only the pull requests whose title names the ticket: an item in `Review` with no such link shows no `PR` segment, and the segment never lists someone else's diff. A title that names no ticket at all is nobody's pull request and is not printed either. + +The segment only ever lists what the ticket owns, so never name another ticket's pull request in a recommendation, in an ask or as a fallback explanation. + +**Ownership is decided per pull request, by its own title - never by comparison.** A ticket can own several at once: `HYPERFLEET-1669` had `hyperfleet-api#416` and `hyperfleet-infra#120` open under its key, and both are its pull requests because both titles name it. The report lists them all and never elects which one is "the real work", never calls one a duplicate and never asks anyone to choose: choosing would mean reading diffs, which the report does not do, and the title is the only rule it applies. The `+N` after a truncated list is a line-width limit, not a ranking - the remaining pull requests are still the ticket's. + +**Jira reports two kinds of record, and the script reads both.** The GitHub app posts through `dev-status` - every repository, with a `status`; a link attached by hand lives in `remotelink` - no status. Reading only `remotelink` is what made `architecture#255` visible and every `hyperfleet-api` pull request invisible, so both are merged and deduplicated by URL. + +**When Jira reports a state, print it.** `PR [#181](url) (merged)` and `PR [#177](url)` say different things: one is a ticket waiting for its status, the other a ticket waiting for a reviewer. A remote link carries no state, so the suffix is absent there - unknown, not open. Never invent one. + +When the lookup fails, the Method section says so in its own `signal: partial` line instead of silently dropping the link. A pull request with no state is not proof of an open one: it is one Jira cannot classify, which is why the suffix is missing rather than `(open)`. ## 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 by [End Date] (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](url) (Status), [KEY](url) (Status) + +#### Highest-priority open items +- 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 +#### Stale in progress/review +- KEY: [Summary] - [Owner or UNASSIGNED] - [Status] - [X days without movement] - PR [#N](url) -#### Carry-Over Risk -- Tickets likely to spill: X -- Story points at risk: X +#### Missing data +- Unestimated open items: X +- Unassigned open items: X / X SP + +### Carry-Over and Capacity +```text +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) +``` + +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, or role when the group decides] +- [Action] - decided by: [Name, or role when the group decides] diff --git a/hyperfleet-jira/scripts/jira_common.py b/hyperfleet-jira/scripts/jira_common.py new file mode 100644 index 0000000..bc8271b --- /dev/null +++ b/hyperfleet-jira/scripts/jira_common.py @@ -0,0 +1,1060 @@ +#!/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.parse +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: + """Read the project-specific workflow status name.""" + return ((doc["fields"].get("status") or {}).get("name") or "").strip() + + +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: + """Run the fixed Jira CLI without exposing its output in failure messages.""" + if binary != "jira": + raise JiraError("only the jira executable is supported") + command = { + ("issue", "list"): "jira issue list", + ("issue", "view"): "jira issue view", + ("sprint", "list"): "jira sprint list", + }.get(tuple(args[:2]), "jira command") + try: + proc = subprocess.run( + [binary, *args], capture_output=True, text=True, timeout=120 + ) + except subprocess.TimeoutExpired: + raise JiraError(f"{command} timed out after 120 seconds") from None + except OSError: + raise JiraError(f"{command} could not be started") from None + if proc.returncode != 0: + raise JiraError(f"{command} failed (exit status {proc.returncode})") + return proc.stdout + + +def parse_date(value: str) -> date: + """Read the calendar date from an ISO date or Jira timestamp.""" + return datetime.strptime(value[:10], "%Y-%m-%d").date() + + +def key_number(key: str) -> int: + """Extract an issue's numeric suffix for key-range pagination.""" + _, _, number = key.rpartition("-") + return int(number) + + +def jql_project(project: str) -> str: + """Build the project clause using a validated project key.""" + 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]: + """Read sprint metadata from the Jira CLI's tab-separated output.""" + 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: + """Select an active sprint, warning when the project has several.""" + 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: + """Read one issue as JSON, reporting failures without response contents.""" + try: + return json.loads( + run_jira(["issue", "view", key, "-p", project, "--raw"], binary) + ) + except JiraError as exc: + raise JiraError(f"could not read {key}: {exc}") from None + except json.JSONDecodeError: + raise JiraError(f"could not read {key}: invalid JSON response") from None + + +def fetch_all( + keys: list[str], + project: str, + binary: str, + jobs: int, + failures: dict[str, str] | None = None, +) -> dict[str, dict]: + """Read every key, keeping the ones that answer. + + A key the caller cannot see - a link target outside their permission, a + deleted issue, a repository the token lost access to - must not abort a report + about the rest. The failed keys go to `failures` when the caller passes a dict, + so the report can say it is partial; a caller that passes none gets a warning + on stderr instead of a traceback. + + Callers must read a missing key as unknown, never as closed: `open_links` + already counts an unread link as open, which keeps a blocker visible with a + status of `?` instead of silently clearing it. + """ + unique = sorted(set(keys), key=key_number) + + def fetch(key: str) -> dict | None: + """Read one issue or record its sanitized failure and continue.""" + try: + return fetch_issue(key, project, binary) + except JiraError as exc: + if failures is not None: + failures[key] = str(exc) + else: + print(f"warning: {exc}", file=sys.stderr) + return None + + with ThreadPoolExecutor(max_workers=jobs) as pool: + docs = list(pool.map(fetch, unique)) + return {doc["key"]: doc for doc in docs if doc is not None} + + +# -------------------------------------------------------------------------- +# 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. + `status_changed_at` keeps the time of that same change: a sprint closes at a + given instant, and a point closed hours later on the same day is not delivered. + + `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, + # Jira's numeric id, which the development panel is keyed by. + "issue_id": str(doc.get("id") or "") or None, + "summary": (fields.get("summary") or "").strip(), + "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", ""), + "created": (fields.get("created") or "")[:10], + "status_changed": status_changed.isoformat(), + "status_changed_at": fields.get("statuscategorychangedate") or None, + "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): + """Reject a redirect before credentials can reach another host.""" + 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 + + if not isinstance(payload, dict): + raise ChangelogUnavailable(f"{key}: MalformedResponse") + changelog = payload.get("changelog") or {} + if not isinstance(changelog, dict): + raise ChangelogUnavailable(f"{key}: MalformedResponse") + histories = changelog.get("histories") or [] + if not isinstance(histories, list): + raise ChangelogUnavailable(f"{key}: MalformedResponse") + 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: + if not isinstance(entry, dict): + raise ChangelogUnavailable(f"{key}: MalformedResponse") + changed_status = changed_assignee = False + changes = entry.get("items") or [] + if not isinstance(changes, list): + raise ChangelogUnavailable(f"{key}: MalformedResponse") + for change in changes: + if not isinstance(change, dict): + raise ChangelogUnavailable(f"{key}: MalformedResponse") + if change.get("field") == "status": + for field in ("fromString", "toString"): + value = change.get(field) + if value is not None and not isinstance(value, str): + raise ChangelogUnavailable(f"{key}: MalformedResponse") + 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 or changed_assignee: + # A movement entry without a readable date must be counted, not + # skipped: skipping it would report the item as "no entry" and let + # the caller fall back to a different clock. + try: + changed_date = parse_date(entry["created"]) + except (KeyError, TypeError, ValueError) as exc: + raise ChangelogUnavailable(f"{key}: MalformedResponse") from exc + if changed_status: + status_dates.append(changed_date) + if changed_assignee: + assignment_dates.append(changed_date) + + 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) + + +PR_URL = re.compile(r"/pull/(\d+)") + + +def key_in_title(key: str, title: str) -> bool: + """Whether `title` names `key`, and not a longer key that starts with it.""" + return bool(re.search(rf"{re.escape(key)}(?!\d)", title or "", re.IGNORECASE)) + + +def pull_requests_from(payload: list, key: str) -> list[dict]: + """The pull requests `key` owns, from a remote-link payload. + + Two filters, because the payload 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 decides ownership. 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 - and then it is 1636's and never 1669's. A title that names + another ticket, or names none at all, leaves this ticket with no pull + request; printing it here would send the reviewer to someone else's diff and + make two stalls look like one shared blocker. + + Remote links are the smaller half of the panel: the GitHub app reports through + `dev-status`, which `development_pull_requests` reads. Both are merged, because + some links exist only here. + + A pull request is identified by its URL, because numbers restart in every + repository: `hyperfleet-api#120` and `hyperfleet-infra#120` can both belong to + one ticket, and keeping only one of them would hide the other's reviewers. + """ + owned: dict[str, int] = {} + for link in payload or []: + if not isinstance(link, dict): + continue + 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 key_in_title(key, obj.get("title") or ""): + # Keyed by URL, not by number: numbers restart in every repository, + # so `hyperfleet-api#120` and `hyperfleet-infra#120` are two pull + # requests and keeping one of them would hide the other's reviewers. + owned.setdefault(url, int(match.group(1))) + return [ + {"number": number, "url": url} + for url, number in sorted(owned.items(), key=lambda pair: (-pair[1], pair[0])) + ] + + +def application_types(summary) -> list[str] | None: + """The application ids the `dev-status` summary lists, or None when malformed. + + Each level is checked on its own: a response can be valid JSON and still be a + list, a string or an object nested the wrong way, and `summary["summary"]` is + not an object just because the body was. + + A branch that is simply absent means "no application reported a pull request", + which is an empty list: Jira answers `{"summary": {}}` for an issue no app has + touched, and calling that malformed would turn a knowable "no pull request" + into an unknown one. + """ + node = summary + for part in ("summary", "pullrequest", "byInstanceType"): + if node is None: + return [] + if not isinstance(node, dict): + return None + node = node.get(part) + if node is None: + return [] + if not isinstance(node, dict): + return None + return list(node) + + +def development_pull_requests(issue_id: str, api: tuple[str, str]) -> tuple[list[dict], str | None]: + """(pull requests the development panel reports, error). + + The panel is served by `dev-status`, not by remote links: the GitHub app posts + its own records there, and they are the ones carrying every repository. On + Sprint 19 the remote links held nothing from `hyperfleet-api`, so ten API items + looked like they had no pull request while theirs were open. + + `applicationType` is not a constant - it is the instance id the app reports + (`oAuth-com.github.integration.production` here, `GitHub` elsewhere) - so the + summary call supplies it instead of a guess. The same records carry `status`, + which is the one thing remote links never have. + """ + server, auth = api + headers = {"Authorization": f"Basic {auth}", "Accept": "application/json"} + + def get(url: str): + """Read authenticated development-panel JSON without redirects.""" + request = urllib.request.Request(url, headers=headers) + with open_changelog(request) as response: + return json.load(response) + + failures = ( + urllib.error.URLError, + http.client.HTTPException, + OSError, + ValueError, + ) + + try: + summary = get(f"{server}/rest/dev-status/1.0/issue/summary?issueId={issue_id}") + except failures as exc: + # The summary is the only source of application ids, so this failure really + # does mean nothing was read. + return [], type(exc).__name__ + + types = application_types(summary) + if types is None: + # A malformed summary is a failed summary read: without the ids there is + # nothing to ask for, and the caller reports a partial read. + return [], "MalformedResponse" + found: list[dict] = [] + error: str | None = None + for app in types: + try: + detail = get( + f"{server}/rest/dev-status/latest/issue/detail?issueId={issue_id}" + f"&applicationType={urllib.parse.quote(app)}&dataType=pullrequest" + ) + except failures as exc: + # One application failing must not discard what the others reported, + # and the caller still needs to know the list is partial. + error = error or type(exc).__name__ + continue + if not isinstance(detail, dict): + # Valid JSON, wrong shape: a list or a string where the panel's object + # belongs. That is a failed application read like any other, and + # calling `.get` on it would abort the whole collector. + error = error or "MalformedResponse" + continue + for group in detail.get("detail") or []: + if not isinstance(group, dict): + continue + reported = group.get("pullRequests") + if isinstance(reported, list): + found.extend(pr for pr in reported if isinstance(pr, dict)) + + prs = [] + for pr in found: + url = (pr.get("url") or "").strip() + match = PR_URL.search(url) + if not match: + continue + prs.append( + { + "number": int(match.group(1)), + "url": url, + "title": pr.get("name") or "", + "status": (pr.get("status") or "").upper() or None, + "updated": pr.get("lastUpdate") or "", + "reviewers": requested_reviewers(pr), + } + ) + return prs, error + + +def requested_reviewers(pr: dict) -> list[str]: + """The people a pull request is waiting on, in the order Jira lists them. + + Three entries never belong in an ask: + + - the author, because nobody approves their own diff + - `approved: true`, because that reviewer already decided + - Jira's `User ` placeholder, which is what the panel shows for a GitHub + account it can no longer resolve. On Sprint 19 most reviewers were this + placeholder, so keeping it would fill the ask with a name nobody answers to. + """ + author = ((pr.get("author") or {}).get("name") or "").strip() + names: list[str] = [] + for reviewer in pr.get("reviewers") or []: + name = ((reviewer or {}).get("name") or "").strip() + if not name or name == "User" or name == author: + continue + if reviewer.get("approved"): + continue + if name not in names: + names.append(name) + return names + + +def read_pull_requests( + key: str, issue_id: str | None, api: tuple[str, str] | None +) -> tuple[list[dict], str | None]: + """(pull requests of `key`, error). + + The panel shows two kinds of record, and a ticket can have both: the GitHub app + posts through `dev-status` (every repository, with a state), and a link the + team attached by hand lives in `remotelink` (no state). Reading only the second + is what hid every `hyperfleet-api` pull request on Sprint 19. + + Ownership comes from the title on both sides - see `pull_requests_from` - so a + link titled for another ticket contributes a state to that ticket, not a pull + request to this one. The state is why the two are merged instead of one being + dropped: it says whether the diff a reviewer opens is still open. + + A failure in one source is returned with whatever the other source found. The + error means "partial", not "empty": dropping the panel's list because the + remote links failed - or the reverse - would hide pull requests Jira does report. + """ + 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"}, + ) + remote_error: str | None = None + try: + with open_changelog(request) as response: + payload = json.load(response) + except ( + urllib.error.URLError, + http.client.HTTPException, + OSError, + ValueError, + ) as exc: + # Keep going: the panel may still answer, and half the list is better + # than none as long as the signal says the read was partial. + payload = [] + remote_error = f"{key}: {type(exc).__name__}" + + owned = pull_requests_from(payload, key) + states: dict[str, dict] = {} + panel_error: str | None = None + if issue_id: + panel, error = development_pull_requests(issue_id, api) + if error: + # Same rule in the other direction: a panel failure must not drop the + # remote-link pull requests already read. `panel` keeps whatever the + # application types that did answer reported. + panel_error = f"{key}: {error}" + for pr in panel: + if key_in_title(key, pr["title"]): + owned.append({"number": pr["number"], "url": pr["url"]}) + states[pr["url"]] = pr + + unique: dict[str, dict] = {} + for pr in owned: + record = {"number": pr["number"], "url": pr["url"]} + state = states.get(pr["url"]) + if state: + record["status"] = state["status"] + record["updated"] = state["updated"] + record["reviewers"] = state["reviewers"] + unique.setdefault(pr["url"], record) + + # Numbers restart in every repository, so they only break ties: a pull request + # is newest by its own last update when Jira reports one. + ordered = sorted( + unique.values(), + key=lambda pr: (pr.get("updated") or "", pr["number"]), + reverse=True, + ) + return ordered, remote_error or panel_error + + +def apply_pull_requests(items: list[dict], jobs: int) -> dict: + """Attach `pr` to the items in review; other items get an empty list. + + `pr` is ownership - the title names the ticket. An item in Review with an empty + list carries no pull request Jira knows about, which is not the same as no pull + request: a repository without the GitHub app reports nothing here. + + `pr_unknown` marks the second case: the lookup for that item did not answer, so + an empty `pr` says "unread", not "none". A partial read can do both - one source + answered and the item keeps what it found while the flag records the failure - + which is why the flag is per item and not only on the returned signal. + + The caller passes what it needs, not only the queue: a blocker in Review is + someone else's pull request, and the ask that names its reviewers needs the + same read. Extra descriptors are cheap - the lookup only touches Review items. + """ + for item in items: + item["pr"] = [] + item["pr_unknown"] = False + + 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: + for item in in_review: + item["pr_unknown"] = True + 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"], item.get("issue_id"), api), + in_review, + ) + ) + + failed = found = 0 + for item, (prs, error) in zip(in_review, results): + if error: + failed += 1 + item["pr_unknown"] = True + 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`. + + The state rides along when Jira reports one, because it changes what the reader + does next: `PR #181 (merged)` is a ticket waiting for its status, `PR #177` is + one waiting for a reviewer. Remote links carry no state, so the suffix is + absent there - not "open", just unknown. + """ + number, url = pr["number"], pr["url"] + if style == "bare": + ref = f"#{number} ({url})" + elif style == "slack": + ref = f"<{url}|#{number}>" + else: + ref = f"[#{number}]({url})" + state = (pr.get("status") or "").lower() + return f"{ref} ({state})" if state and state != "open" else ref + + +def pr_refs(item: dict, style: str) -> str: + """`PR #1, #2 +1` for an item, or "" when Jira reports no pull request. + + The two shown are a line-width cap, not a choice: every pull request in the + list belongs to the ticket by its own title, and the count after `+` says how + many are not shown. Nothing is dropped from ownership, only from the line. + """ + prs = item.get("pr") or [] + if not prs: + return "" + shown = ", ".join(pr_ref(pr, style) for pr in prs[:2]) + more = f" +{len(prs) - 2}" if len(prs) > 2 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. + + `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 + + +def iso_date(value: str) -> str: + """Validate a CLI date without changing it: `build` re-parses it with `parse_date`.""" + try: + datetime.strptime(value, "%Y-%m-%d") + except ValueError as exc: + raise argparse.ArgumentTypeError(f"not a YYYY-MM-DD date: {value!r}") from exc + return value + + +def positive_int(value: str) -> int: + """A thread count of zero is a crash inside the pool, not a valid argument.""" + try: + number = int(value) + except ValueError as exc: + raise argparse.ArgumentTypeError(f"not an integer: {value!r}") from exc + if number < 1: + raise argparse.ArgumentTypeError(f"must be at least 1: {value!r}") + return number + + +# -------------------------------------------------------------------------- +# CLI surface and signals shared by both collectors +# -------------------------------------------------------------------------- + + +def add_common_arguments(parser: argparse.ArgumentParser) -> None: + """The flags both collectors accept, written once. + + Two `--help` texts that drift are two contracts: the reviewer reads one and + the lead runs the other. The flags that mean the same thing in both scripts + live here; the ones that only one command has stay in its `main`. + """ + parser.add_argument("--project", default="HYPERFLEET", type=project_key) + parser.add_argument( + "--jira", default="jira", choices=["jira"], + help="only the jira executable from PATH is supported", + ) + parser.add_argument( + "--sp-field", default="customfield_10028", help="custom field id holding story points" + ) + parser.add_argument("--today", type=iso_date, 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("--jobs", type=positive_int, default=8) + + +def no_prs_signal() -> dict: + """The `pr_signal` of a run that skipped the lookup. + + `skipped` is what keeps the renderer from blaming a missing token for a call + the caller turned off. + """ + return {"available": True, "failed": 0, "checked": 0, "found": 0, "skipped": True} + + +def warn_changelog_failure(signal: dict) -> None: + """Say once, on stderr, that some movement clocks fell back.""" + if not signal.get("failed"): + return + print( + f"warning: {signal['failed']} of {signal['checked']} changelog reads " + "failed; those items fall back to the status category date", + file=sys.stderr, + ) diff --git a/hyperfleet-jira/scripts/pulse_check.py b/hyperfleet-jira/scripts/pulse_check.py new file mode 100755 index 0000000..8cbe635 --- /dev/null +++ b/hyperfleet-jira/scripts/pulse_check.py @@ -0,0 +1,644 @@ +#!/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 markdown # 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 json +import sys +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, + JiraError, + active_sprint, + add_common_arguments, + apply_changelog_signals, + apply_pull_requests, + describe, + fetch_all, + jira_base_url, + no_prs_signal, + open_links, + parse_date, + pr_refs, + search_keys, + ticket_ref, + warn_changelog_failure, +) + +# 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: + """Collapse whitespace so a value fits on one report line.""" + 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 large_item_keys( + project: str, sprint_id: str, min_sp: int, sp_field_name: str, binary: str +) -> list[str]: + """Every large item in the sprint, past the 100-issue page cap. + + `jira issue list` truncates a sprint above 100 issues without saying so; + `search_keys` moves the JQL window instead, and raises rather than returning a + short list that looks complete. + """ + jql = ( + f'project = {project} AND sprint = {sprint_id} ' + f'AND "{sp_field_name}" >= {min_sp} AND {OPEN_STATUS_JQL}' + ) + return search_keys(jql, project, binary) + + +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]")) + + +# A merged or declined diff is nobody's next decision: the ticket needs a status, +# not a reviewer. Jira reports "OPEN" and the two closed states for the GitHub app, +# and nothing at all for a link attached by hand. +CLOSED_STATES = ("MERGED", "DECLINED") + + +def live_pull_requests(item: dict) -> list[dict]: + """The pull requests of `item` that a reviewer can still act on.""" + return [ + pr + for pr in item.get("pr") or [] + if (pr.get("status") or "").upper() not in CLOSED_STATES + ] + + +def reviewers_of(item: dict) -> list[str]: + """Everyone the ticket's live pull requests are waiting on, without repeats. + + An item can own several open pull requests in different repositories, each with + its own reviewers; the ask speaks for the ticket, so the union is what it names. + """ + names: list[str] = [] + for pr in live_pull_requests(item): + for name in pr.get("reviewers") or []: + if name not in names: + names.append(name) + return names + + +def given_names(reviewers: list[str]) -> str: + """`Tirth`, `Tirth and Rafael`, `Tirth, Rafael and Martin`. + + First names keep the table cell readable, which is the same reason the Owner + column shows one. The pull request is linked beside the ask, so a reader who + needs the full identity has it one click away. + """ + firsts: list[str] = [] + for full in reviewers: + parts = (full or "").split() + if not parts: + continue + first = parts[0] + if first not in firsts: + firsts.append(first) + if len(firsts) <= 1: + return "".join(firsts) + return f"{', '.join(firsts[:-1])} and {firsts[-1]}" + + +def suggested_ask(item: dict, ref=None, style: str = "bare") -> str: + """One imperative per item: verb first, then who and what artifact. + + The verb comes from a fixed set - ask to approve/reject, assign, attach a pull + request, move out of Review, post, start, propose a split, confirm - 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. + + Who the ask names follows the state: a blocker in `Review` names every + requested reviewer Jira reports, because the owner of that ticket wrote the + diff; the owner is named only when Jira reports no pull request at all. + + `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. + + A blocker whose pull request read did not answer is `pr_unknown`: the ask + cannot name a reviewer, and naming its owner would name the author when the + diff exists but was not read. Reviewers a partial read still found are named + first, because they are facts the read did return. + + A blocker in Review whose pull requests are all closed is the queue's case + again: nobody can review a merged or declined diff, so the ask moves the + ticket out of Review instead of asking its owner to approve it. + """ + 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( + 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.get("unread"): + # The target could not be read, so "assign it" would order work that + # may already have an owner and a status. Ask for the read instead: + # the status is what the next pulse needs before it can ask anything. + clauses.append(f"confirm {ref(d['key'])}'s status and owner") + continue + if d["status"] == "Review": + # The reviewer moves this ticket; the owner is usually the author. + # Jira reports every requested reviewer, so the ask names all of + # them instead of picking one - the choice of who reviews stays + # with them. + names = given_names(d.get("reviewers") or []) + if names: + # Reviewers a partial read still found are facts, so they win + # over the unknown flag: the ask names them and stops there. + clauses.append( + f"ask {names} to approve or reject {ref(d['key'])} (Review{when})" + ) + elif d.get("pr_unknown") or d.get("has_live_pr"): + # Unread (`--no-prs`, missing token, failed read) or a live + # pull request Jira lists no reviewer for: a name here would + # be the author. + clauses.append( + f"ask a reviewer to approve or reject {ref(d['key'])} (Review{when})" + ) + elif d.get("pr"): + # Every pull request this blocker owns is closed, so the ticket + # needs a status, not a reviewer - the same move the queue path + # in `decorate_ask` makes. Asking its owner to approve a merged + # diff would send them to finished work. + prs = pr_refs({"pr": d["pr"]}, style) + clauses.append(f"move {ref(d['key'])} out of Review: {prs}") + elif d.get("owner"): + clauses.append( + f"ask {d['owner'].split()[0]} to approve or reject {ref(d['key'])} " + f"(Review{when})" + ) + else: + clauses.append(f"assign {ref(d['key'])}") + elif not d.get("owner"): + clauses.append(f"assign {ref(d['key'])}") + elif d["status"] == "In Progress": + 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 {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 + 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 decorate_ask(item: dict, style: str) -> str: + """Fold the pull request a reviewer can act on into the ask. + + Ownership comes from the title, so a link Jira shows that is titled for another + ticket is not this ticket's pull request and never appears here: the reviewer + it named would open someone else's diff. + + The ask carries the pull requests a reviewer can act on, which is not the same + as every pull request the ticket owns. A ticket that merged `infra#122` and + then opened `e2e#177` owns both, but "approve or reject #122 (merged)" sends + the reader to a closed diff. Closed ones stay in the report line; only the live + ones become the ask. When every one of them is closed, the ticket needs a + status, not a reviewer. + + With a live pull request the ask names the reviewers waiting on it, all of + them: choosing one would decide who reviews. + + With no pull request at all, the ask says "Jira links none", not "there is + none": the panel is the only source this script reads, and the two moves an + owner can make are the same either way - attach the pull request, or move the + ticket back. + + A read that did not answer is not "no pull request": `pr_unknown` keeps the + ask neutral instead of asking the owner to attach a diff that may already + exist. + """ + ask = item["ask"] + owned = list(item.get("pr") or []) + live = live_pull_requests(item) + if live: + # 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. + prs = pr_refs({"pr": live}, style) + names = given_names(reviewers_of(item)) + if names and ask.startswith("Ask a reviewer"): + # Same rule as a blocker in Review: name every requested reviewer, + # never the owner, who is the author of the diff being reviewed. + return f"Ask {names} to approve or reject {prs}" + if ask.startswith("Ask a reviewer"): + return f"{ask} {prs}" + return f"{ask} - {prs}" + if item.get("pr_unknown"): + # A partial read still decorates what it found (the branch above); an + # empty one is unknown, not empty, so neither "attach" nor "move back" + # can be inferred. + return ask + if owned: + # Asking for review of a closed diff sends the reader to finished work. + # What the ticket needs is a status, not a reviewer. + return f"Move this ticket out of Review: {pr_refs(item, style)}" + if item.get("status") == "Review" and ask.startswith("Ask a reviewer"): + return "Attach this ticket's pull request, or move it back to In Progress" + return ask + + +def build(args) -> dict: + """Collect sprint signals and derive the nudge queue and allocation gaps.""" + 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, sprint["id"], args.min_sp, args.sp_field_name, args.jira + ) + fetch_failures: dict[str, str] = {} + docs = fetch_all(keys, args.project, args.jira, args.jobs, fetch_failures) + + 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, fetch_failures) + if targets + else {} + ) + + # 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} + category_of = {key: entry["category"] for key, entry in by_key.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) + warn_changelog_failure(signals) + + base_url = jira_base_url() + + def ref(key: str) -> str: + """Render an ask's ticket link in the requested destination style.""" + 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"]) + item["blocks_open"] = open_links(item["blocks"], category_of) + + # A blocker in Review is a pull request someone else has to decide on, so the + # ask has to name that ticket's reviewers. The panel is already read for the + # queue, and reading the blockers' takes the same call - without it the ask + # falls back to the blocker's owner, who is usually the author of the diff. + review_keys = {item["key"] for item in items if item["status"] == "Review"} + review_keys |= { + key + for item in items + for key in item["blocked_by"] + if by_key.get(key, {}).get("status") == "Review" + } + pr_targets = [by_key[key] for key in sorted(review_keys) if key in by_key] + if args.no_prs: + pr_signal = no_prs_signal() + for target in pr_targets: + # The lookup was turned off, which is one more way of not knowing: + # the ask must not read the empty list as "no pull request". + target["pr"] = [] + target["pr_unknown"] = True + else: + pr_signal = apply_pull_requests(pr_targets, args.jobs) + + for item in items: + item["blocker_detail"] = [ + { + "key": k, + "status": by_key[k]["status"] if k in by_key else "?", + "owner": (by_key[k]["owner"] or None) if k in by_key else None, + "days_in_status": by_key[k]["days_in_status"] if k in by_key else None, + "reviewers": reviewers_of(by_key[k]) if k in by_key else [], + "pr": list(by_key[k].get("pr") or []) if k in by_key else [], + "has_live_pr": bool(live_pull_requests(by_key[k])) if k in by_key else False, + "pr_unknown": bool(by_key[k].get("pr_unknown")) if k in by_key else True, + # An unread target has no owner to name and no status to trust: + # `assign` here could order work that someone already owns. + "unread": k not in by_key, + } + for k in item["open_blockers"] + ] + item["ask"] = suggested_ask(item, ref, args.link_style) + item["ask"] = decorate_ask(item, args.link_style) + + 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": 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, + "pr_signal": pr_signal, + "fetch_signal": { + "failed": len(fetch_failures), + "keys": sorted(fetch_failures), + }, + "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: + """Render collected pulse data without additional Jira reads.""" + 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") + + def ref(key: str) -> str: + """Render a ticket link using the report's URL and link style.""" + return ticket_ref(key, base_url, style) + + 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"{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"]: + 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"]: + 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"]: + 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"{ref(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("") + 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" + ) + 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'})" + ) + fetches = data.get("fetch_signal") or {} + if fetches.get("failed"): + lines.append( + f"Signal: partial - {fetches['failed']} issue reads failed, so those items " + "are missing from the queue and their links stay open" + ) + lines.append(data["definition"]) + lines.append(f"Next pulse: {data['next_pulse'] or 'to be scheduled'}") + return "\n".join(lines) + + +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: + """Validate arguments and emit the pulse report or a sanitized error.""" + parser = argparse.ArgumentParser(description="Collect the sprint pulse check data.") + add_common_arguments(parser) + 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-name", default="Story Points", type=field_name, help="JQL name of the story points field") + 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( + "--format", + choices=["json", "markdown", "text"], + default="json", + help="markdown and text are the same ready-to-paste block", + ) + args = parser.parse_args() + + try: + data = build(args) + except PulseError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + print( + json.dumps(data, indent=2, ensure_ascii=False) + if args.format == "json" + else render_text(data) + ) + 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..b81a1c4 --- /dev/null +++ b/hyperfleet-jira/scripts/sprint_status.py @@ -0,0 +1,834 @@ +#!/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 json +import re +import sys +from datetime import date, datetime, timezone + +# 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, + JiraError, + active_sprint, + add_common_arguments, + apply_changelog_signals, + apply_pull_requests, + describe, + fetch_all, + jira_base_url, + jql_project, + no_prs_signal, + open_links, + parse_date, + pr_refs, + search_keys, + sprint_rows, + status_category, + status_name, + ticket_ref, + warn_changelog_failure, +) + +# 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( + 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"]) + + +def sprint_of(doc: dict, sprint_id: str) -> dict | None: + """Find a sprint's metadata in an issue's sprint field.""" + for sprint in doc["fields"].get("customfield_10020") or []: + if str(sprint.get("id")) == str(sprint_id): + return sprint + return None + + +def resolve_blockers( + items: list[dict], + docs: dict[str, dict], + project: str, + binary: str, + jobs: int, + failures: dict[str, str] | None = None, +) -> 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, failures) if targets else {} + ) + + status_of = { + key: { + "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"] = open_links(item["blocked_by"], category_of) + item["blocked"] = bool(item["open_blockers"]) + + +# -------------------------------------------------------------------------- +# Aggregates +# -------------------------------------------------------------------------- + + +def summarise(items: list[dict]) -> dict: + """Aggregate item and point totals by status and status category.""" + 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]: + """Group workload by owner, with unassigned work listed last.""" + 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 sprint_closed_at(sprint: dict, docs: dict[str, dict]) -> str | None: + """The instant Jira recorded the sprint closing, not its planned end. + + `jira sprint list` prints the planned end, and the two are not the same: Sprint + 18 was planned to 2026-11-01 and closed on 2026-11-02, so HYPERFLEET-1731's + point, closed the morning after the plan ran out, fell outside the baseline. + `completeDate` is the recorded close, and every issue carries it in its sprint + field, so reading it costs no extra request. + + The planned end is the fallback for a sprint whose issues are gone or whose + records predate `completeDate`. + """ + for doc in docs.values(): + record = sprint_of(doc, sprint["id"]) + if record and record.get("completeDate"): + return record["completeDate"] + return sprint.get("end") + + +def close_instant(value: str | None) -> datetime | None: + """The baseline cutoff as an instant, in UTC. + + Jira timestamps carry an offset (`+0000`), and the close is a moment, not a + day: a point closed at 14:11 on the day the sprint closed at 08:49 belongs to + the next sprint. `jira sprint list` keeps no time in its `END` column, so a + bare date there means the end of that day - a sprint is not over at midnight on + the day it ends. + """ + if not value: + return None + text = value.strip() + if len(text) <= 10: + try: + day = parse_date(text) + except ValueError: + return None + return datetime(day.year, day.month, day.day, 23, 59, 59, tzinfo=timezone.utc) + # `fromisoformat` reads `+0000` only in newer Pythons; the colon is free. + normalized = re.sub(r"([+-]\d{2})(\d{2})$", r"\1:\2", text.replace("Z", "+00:00")) + try: + parsed = datetime.fromisoformat(normalized) + except ValueError: + return None + return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) + + +def baseline_for( + sprint: dict | None, + project: str, + sp_field: str, + binary: str, + jobs: int, + today: date, + failures: dict[str, str] | None = None, +) -> dict | None: + """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. + + "Ended" is the close Jira recorded (`completeDate`), not the planned end - see + `sprint_closed_at`. A sprint that ran past its plan still counts the work that + landed before it was closed. + """ + 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, failures) + items = [describe(doc["key"], doc, sp_field, today) for doc in docs.values()] + committed = sum(item["sp"] or 0 for item in items) + closed = sprint_closed_at(sprint, docs) + cutoff = close_instant(closed) + delivered = sum( + item["sp"] or 0 + for item in items + if item["is_done"] and _closed_by(item["status_changed_at"], cutoff) + ) + try: + days = (parse_date(closed) - parse_date(sprint["start"])).days + 1 + except (KeyError, TypeError, ValueError): + days = None + return { + "sprint": sprint["name"], + "id": sprint["id"], + "end": closed[:10] if closed else None, + "items": len(items), + "committed_sp": committed, + "delivered_sp": delivered, + "percent": round(100 * delivered / committed, 1) if committed else 0.0, + "days": days, + } + + +def _closed_by(status_changed_at: str | None, cutoff: datetime | None) -> bool: + """True when the item entered Done on or before `cutoff`. + + Compared as instants, not days: a point closed at 14:11 on the day the sprint + closed at 08:49 is next sprint's delivery. + + Without a readable cutoff there is nothing to compare against, so the item + counts: an unparsed value must not silently report zero delivery. + """ + if cutoff is None: + return True + if not status_changed_at: + return False + instant = close_instant(status_changed_at) + if instant is None: + return False + return instant <= cutoff + + +# -------------------------------------------------------------------------- +# Report +# -------------------------------------------------------------------------- + + +def build(args) -> dict: + """Collect sprint data and derive progress, risks and baseline capacity.""" + 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) + fetch_failures: dict[str, str] = {} + docs = fetch_all(keys, args.project, args.jira, args.jobs, fetch_failures) + items = [describe(doc["key"], 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, fetch_failures) + signals = apply_changelog_signals( + [item for item in items if not item["is_done"]], today, args.jobs + ) + warn_changelog_failure(signals) + + totals = summarise(items) + open_items = [item for item in items if not item["is_done"]] + pr_signal = no_prs_signal() if args.no_prs else apply_pull_requests(open_items, args.jobs) + 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, sprint.get("start") or None) + if not args.no_baseline + else None, + args.project, + args.sp_field, + args.jira, + args.jobs, + today, + fetch_failures, + ) + + 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, + "pr_signal": pr_signal, + "fetch_signal": { + "failed": len(fetch_failures), + "keys": sorted(fetch_failures), + }, + "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. " + "delivered_sp counts only work Done by the previous sprint's end date, " + "so work closed later is not credited to it" + ), + }, + } + + +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: + """Render collected sprint data without additional Jira reads.""" + sprint = data["sprint"] + totals = data["totals"] + base_url = data.get("jira_base_url") + style = data.get("link_style", "markdown") + + def ref(key: str) -> str: + """Render a ticket link using the report's URL and link style.""" + return ticket_ref(key, base_url, style) + + def pr_tail(item: dict) -> str: + """Append the item's pull request references when present.""" + rendered = pr_refs(item, style) + return f" - {rendered}" if rendered else "" + + 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: + 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{cutoff} ({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"{ref(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}{pr_tail(item)}" + ) + 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){pr_tail(item)}" + ) + 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){pr_tail(item)}" + ) + 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 counted in multiple reasons)" + ) + + 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']}") + 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" + ) + 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'})" + ) + fetches = data.get("fetch_signal") or {} + if fetches.get("failed"): + lines.append( + f"- signal: partial - {fetches['failed']} issue reads failed, so those items " + "are missing and their links stay open" + ) + return "\n".join(lines) + + +def main() -> int: + """Validate arguments and emit sprint status or a sanitized error.""" + parser = argparse.ArgumentParser(description="Collect the sprint status data.") + add_common_arguments(parser) + parser.add_argument("--sprint", help="sprint id; defaults to the active sprint") + 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("--no-baseline", action="store_true", help="skip the previous sprint lookup") + 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", "markdown", "text"], + default="json", + help="markdown and text are the same ready-to-paste report", + ) + args = parser.parse_args() + + try: + data = build(args) + except SprintError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + print( + json.dumps(data, indent=2, ensure_ascii=False) + if args.format == "json" + else render_text(data) + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/hyperfleet-jira/tests/run-tests.sh b/hyperfleet-jira/tests/run-tests.sh new file mode 100644 index 0000000..43b9342 --- /dev/null +++ b/hyperfleet-jira/tests/run-tests.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "${PYTHON:-python3}" -m unittest discover -s "$SCRIPT_DIR" -v diff --git a/hyperfleet-jira/tests/test_cli_safety.py b/hyperfleet-jira/tests/test_cli_safety.py new file mode 100644 index 0000000..722f5a3 --- /dev/null +++ b/hyperfleet-jira/tests/test_cli_safety.py @@ -0,0 +1,121 @@ +"""Regression tests for executable selection and private CLI diagnostics.""" + +import io +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) + +import jira_common as jc +import pulse_check as pc +import sprint_status as ss + + +SECRET = "private-token-and-issue-content" + + +class ExecutableTest(unittest.TestCase): + """Both entry points reject executable overrides before any Jira call.""" + + def test_collectors_reject_other_executables_before_running(self): + """Neither shell commands nor absolute executable paths are accepted.""" + for collector in (pc, ss): + for binary in ("sh", "/bin/sh", "/usr/local/bin/jira", "jira; id"): + with self.subTest(collector=collector.__name__, binary=binary), \ + mock.patch.object(sys, "argv", ["collector", "--jira", binary]), \ + mock.patch.object(sys, "stderr", new_callable=io.StringIO), \ + mock.patch.object(jc.subprocess, "run") as run, \ + mock.patch.object(collector, "build") as build: + with self.assertRaises(SystemExit) as caught: + collector.main() + self.assertEqual(caught.exception.code, 2) + run.assert_not_called() + build.assert_not_called() + + def test_collectors_accept_the_fixed_executable(self): + """The default and explicit jira option preserve the supported path.""" + for collector in (pc, ss): + for flags in ([], ["--jira", "jira"]): + with self.subTest(collector=collector.__name__, flags=flags), \ + mock.patch.object(sys, "argv", ["collector", *flags]), \ + mock.patch.object(sys, "stdout", new_callable=io.StringIO), \ + mock.patch.object(collector, "build", return_value={}) as build: + self.assertEqual(collector.main(), 0) + self.assertEqual(build.call_args.args[0].jira, "jira") + + def test_direct_calls_also_reject_other_executables(self): + """The shared runner cannot bypass the parser's restriction.""" + with mock.patch.object(jc.subprocess, "run") as run: + with self.assertRaises(jc.JiraError): + jc.run_jira(["issue", "list"], "/bin/sh") + run.assert_not_called() + + +class DiagnosticsTest(unittest.TestCase): + """Failures reveal only fixed identifiers, never captured CLI contents.""" + + def test_nonzero_exit_does_not_expose_output_or_arguments(self): + """Private command arguments, stdout and stderr stay out of errors.""" + proc = mock.Mock(returncode=1, stdout=SECRET, stderr=SECRET) + with mock.patch.object(jc.subprocess, "run", return_value=proc): + with self.assertRaises(jc.JiraError) as caught: + jc.run_jira(["issue", "list", "-q", SECRET], "jira") + self.assertEqual(str(caught.exception), "jira issue list failed (exit status 1)") + + def test_unknown_command_uses_a_fixed_identifier(self): + """Even an unexpected argument list is not copied to the error.""" + with mock.patch.object(jc.subprocess, "run", return_value=mock.Mock(returncode=2)): + with self.assertRaises(jc.JiraError) as caught: + jc.run_jira([SECRET], "jira") + self.assertEqual(str(caught.exception), "jira command failed (exit status 2)") + + def test_timeout_and_launch_errors_do_not_expose_exception_details(self): + """Exception text and captured output are suppressed on process failures.""" + errors = ( + jc.subprocess.TimeoutExpired(SECRET, 120, output=SECRET, stderr=SECRET), + FileNotFoundError(SECRET), + PermissionError(SECRET), + ) + for error in errors: + with self.subTest(error=type(error).__name__), \ + mock.patch.object(jc.subprocess, "run", side_effect=error): + with self.assertRaises(jc.JiraError) as caught: + jc.run_jira(["issue", "list"], "jira") + self.assertNotIn(SECRET, str(caught.exception)) + self.assertTrue(caught.exception.__suppress_context__) + + def test_unreadable_issue_diagnostics_are_safe_in_both_failure_paths(self): + """Neither the failure map nor fetch_all's warning contains CLI output.""" + for proc in ( + mock.Mock(returncode=1, stdout=SECRET, stderr=SECRET), + mock.Mock(returncode=0, stdout=SECRET), + ): + with self.subTest(returncode=proc.returncode), \ + mock.patch.object(jc.subprocess, "run", return_value=proc), \ + mock.patch.object(sys, "stderr", new_callable=io.StringIO) as stderr: + failures = {} + self.assertEqual(jc.fetch_all(["HYPERFLEET-1"], "HYPERFLEET", "jira", 1, failures), {}) + self.assertNotIn(SECRET, str(failures)) + self.assertIn("HYPERFLEET-1", failures) + self.assertEqual(jc.fetch_all(["HYPERFLEET-1"], "HYPERFLEET", "jira", 1), {}) + self.assertIn("warning:", stderr.getvalue()) + self.assertNotIn(SECRET, stderr.getvalue()) + + def test_both_entry_points_print_only_sanitized_cli_errors(self): + """A real build failure cannot copy private CLI output to the console.""" + proc = mock.Mock(returncode=1, stdout=SECRET, stderr=SECRET) + for collector in (pc, ss): + with self.subTest(collector=collector.__name__), \ + mock.patch.object(sys, "argv", ["collector"]), \ + mock.patch.object(sys, "stderr", new_callable=io.StringIO) as stderr, \ + mock.patch.object(sys, "stdout", new_callable=io.StringIO) as stdout, \ + mock.patch.object(jc.subprocess, "run", return_value=proc): + self.assertEqual(collector.main(), 1) + self.assertEqual(stderr.getvalue(), "error: jira sprint list failed (exit status 1)\n") + self.assertEqual(stdout.getvalue(), "") + + +if __name__ == "__main__": + unittest.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..5717e0a --- /dev/null +++ b/hyperfleet-jira/tests/test_pulse_check.py @@ -0,0 +1,1185 @@ +"""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 tempfile +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 jira_common as jc # noqa: E402 +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 = 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 = 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 = jc.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 = 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 = 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): + 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(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(jc, "jira_api", return_value=self.api), \ + mock.patch.object( + 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) + self.assertEqual(item["days_without_movement"], 4) + self.assertEqual(item["status_entered"], "2026-10-30") + self.assertEqual( + report, + { + "available": True, + "failed": 0, + "checked": 1, + "status_dates": 1, + "assignments": 0, + }, + ) + + def test_assignment_resets_the_clock(self): + item = self.item() + with mock.patch.object(jc, "jira_api", return_value=self.api), \ + mock.patch.object( + 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) + 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(jc, "jira_api", return_value=self.api), \ + mock.patch.object( + 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(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) + 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( + jc, "open_changelog", return_value=self.Response(self.histories()) + ): + self.assertEqual( + jc.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( + jc, "open_changelog", return_value=self.Response(payload) + ): + self.assertEqual( + 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( + jc, "open_changelog", return_value=self.Response(payload) + ): + self.assertEqual( + jc.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 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(jc, "jira_api", return_value=self.api), \ + mock.patch.object( + jc, "changelog_dates", + side_effect=jc.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(jc, "jira_api", return_value=self.api), \ + mock.patch.object( + jc, "changelog_dates", side_effect=jc.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( + jc, + "open_changelog", + side_effect=jc.urllib.error.URLError("401 Unauthorized"), + ): + with self.assertRaises(jc.ChangelogUnavailable): + jc.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(jc, "open_changelog", side_effect=error) + else: + patcher = mock.patch.object( + jc, "open_changelog", return_value=self.Response(payload) + ) + with patcher: + return jc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) + + def test_a_truncated_response_is_counted(self): + with self.assertRaises(jc.ChangelogUnavailable): + 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") + with self.assertRaises(jc.ChangelogUnavailable): + self.call(error=error) + + def test_a_capped_changelog_is_counted(self): + with self.assertRaises(jc.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 = jc.NoRedirect() + with self.assertRaises(jc.urllib.error.HTTPError) as caught: + handler.redirect_request( + jc.urllib.request.Request("https://a.example"), + None, + 302, + "Found", + {}, + "https://b.example", + ) + + +class RunJiraTest(unittest.TestCase): + def test_a_timeout_is_a_pulse_error(self): + with mock.patch.object( + jc.subprocess, + "run", + side_effect=jc.subprocess.TimeoutExpired("jira", 120), + ): + with self.assertRaises(pc.PulseError): + jc.run_jira(["issue", "list"], "jira") + + def test_a_missing_binary_is_a_pulse_error(self): + with mock.patch.object( + jc.subprocess, "run", side_effect=FileNotFoundError("jira") + ): + with self.assertRaises(pc.PulseError): + jc.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(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( + 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(jc.project_key("HYPERFLEET"), "HYPERFLEET") + + def test_jql_is_not_a_project_key(self): + with self.assertRaises(jc.argparse.ArgumentTypeError): + jc.project_key("HF OR project = SECRET") + + +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_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) + 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_an_unread_blocker_asks_for_its_status_not_an_owner(self): + item = { + "summary": "x", + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1825"], + "blocker_detail": [ + {"key": "HYPERFLEET-1825", "status": "?", "owner": None, "unread": True} + ], + } + ask = pc.suggested_ask(item).lower() + # No `assign`: the ticket may already have an owner, the read just failed. + self.assertIn("confirm hyperfleet-1825's status and owner", ask) + self.assertNotIn("assign", ask) + + 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_a_review_blocker_names_every_requested_reviewer(self): + item = { + "summary": "x", + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1709"], + "blocker_detail": [ + { + "key": "HYPERFLEET-1709", + "status": "Review", + "owner": "Phuongnhat Nguyen", + "days_in_status": 5, + "reviewers": ["Tirth Chetan Thakkar", "Rafael Benevides"], + "has_live_pr": True, + } + ], + } + ask = pc.suggested_ask(item) + self.assertIn("Tirth and Rafael to approve or reject", ask) + # The owner of a ticket in Review is the author of the diff, not its reviewer. + self.assertNotIn("Phuongnhat", ask) + + def test_a_review_blocker_without_reviewer_data_does_not_name_the_author(self): + item = { + "summary": "x", + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1636"], + "blocker_detail": [ + { + "key": "HYPERFLEET-1636", + "status": "Review", + "owner": "Martin Liptak", + "days_in_status": 7, + "reviewers": [], + "has_live_pr": True, + } + ], + } + ask = pc.suggested_ask(item) + self.assertIn("a reviewer to approve or reject", ask.lower()) + self.assertNotIn("Martin", ask) + + def test_an_unread_blocker_does_not_name_the_blocker_owner(self): + item = { + "summary": "x", + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1636"], + "blocker_detail": [ + { + "key": "HYPERFLEET-1636", + "status": "Review", + "owner": "Martin Liptak", + "days_in_status": 7, + "reviewers": [], + "has_live_pr": False, + "pr_unknown": True, + } + ], + } + ask = pc.suggested_ask(item) + self.assertIn("a reviewer to approve or reject", ask.lower()) + self.assertNotIn("Martin", ask) + + def test_a_partial_read_still_names_the_reviewers_it_found(self): + item = { + "summary": "x", + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1709"], + "blocker_detail": [ + { + "key": "HYPERFLEET-1709", + "status": "Review", + "owner": "Phuongnhat Nguyen", + "days_in_status": 5, + "reviewers": ["Tirth Chetan Thakkar", "Rafael Benevides"], + "has_live_pr": True, + "pr_unknown": True, + } + ], + } + ask = pc.suggested_ask(item) + self.assertIn("Tirth and Rafael to approve or reject", ask) + self.assertNotIn("Phuongnhat", ask) + + def test_a_review_blocker_with_closed_pull_requests_asks_to_move_it(self): + item = { + "summary": "x", + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1636"], + "blocker_detail": [ + { + "key": "HYPERFLEET-1636", + "status": "Review", + "owner": "Martin Liptak", + "days_in_status": 7, + "reviewers": [], + "pr": [ + { + "number": 181, + "url": "https://github.com/o/r/pull/181", + "status": "MERGED", + } + ], + "has_live_pr": False, + } + ], + } + ask = pc.suggested_ask(item, style="markdown") + # The diff is finished, so no reviewer can act: the blocker needs a status. + self.assertTrue(ask.startswith("Move HYPERFLEET-1636 out of Review"), ask) + self.assertIn("[#181](https://github.com/o/r/pull/181) (merged)", ask) + self.assertNotIn("approve or reject", ask.lower()) + self.assertNotIn("Martin", ask) + + def test_a_review_blocker_still_asks_for_review_when_a_pull_request_is_live(self): + item = { + "summary": "x", + "status": "Backlog", + "days_without_movement": 70, + "open_blockers": ["HYPERFLEET-1636"], + "blocker_detail": [ + { + "key": "HYPERFLEET-1636", + "status": "Review", + "owner": "Martin Liptak", + "days_in_status": 7, + "reviewers": ["Tirth Chetan Thakkar"], + "pr": [ + { + "number": 255, + "url": "https://github.com/o/r/pull/255", + "status": "OPEN", + "reviewers": ["Tirth Chetan Thakkar"], + }, + { + "number": 181, + "url": "https://github.com/o/r/pull/181", + "status": "MERGED", + }, + ], + "has_live_pr": True, + } + ], + } + ask = pc.suggested_ask(item) + self.assertIn("Tirth to approve or reject", ask) + self.assertNotIn("out of Review", 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 PullRequestAskTest(unittest.TestCase): + """Jira links a pull request to every ticket its title names, and only the title decides.""" + + def item(self, pr=(), pr_unknown=False): + return { + "summary": "Read tenant dimensions from wristband claims", + "status": "Review", + "days_without_movement": 4, + "open_blockers": [], + "blocker_detail": [], + "ask": "Ask a reviewer to approve or reject", + "pr": list(pr), + "pr_unknown": pr_unknown, + } + + def test_an_owned_pull_request_rides_in_the_ask(self): + ask = pc.decorate_ask( + self.item(pr=[{"number": 257, "url": "https://github.com/o/r/pull/257"}]), "markdown" + ) + self.assertIn("approve or reject PR [#257]", ask) + + def test_another_tickets_pull_request_never_reaches_the_ask(self): + ask = pc.decorate_ask(self.item(), "markdown") + self.assertNotIn("#255", ask) + self.assertNotIn("1636", ask) + self.assertNotIn("approve or reject PR", ask) + + def test_an_unread_lookup_does_not_infer_a_missing_pull_request(self): + ask = pc.decorate_ask(self.item(pr_unknown=True), "markdown") + self.assertEqual(ask, "Ask a reviewer to approve or reject") + + def test_a_partial_read_still_decorates_the_pull_request_it_found(self): + item = self.item( + pr=[ + { + "number": 416, + "url": "https://github.com/o/r/pull/416", + "status": "OPEN", + "reviewers": ["Tirth Chetan Thakkar"], + } + ], + pr_unknown=True, + ) + ask = pc.decorate_ask(item, "markdown") + self.assertIn("Tirth to approve or reject PR [#416]", ask) + + def test_a_review_item_with_no_pull_request_asks_for_the_missing_artifact(self): + self.assertEqual( + pc.decorate_ask(self.item(), "markdown"), + "Attach this ticket's pull request, or move it back to In Progress", + ) + + def test_a_merged_pull_request_asks_for_a_status_not_a_review(self): + item = self.item( + pr=[{"number": 181, "url": "https://github.com/o/r/pull/181", "status": "MERGED"}] + ) + ask = pc.decorate_ask(item, "markdown") + self.assertTrue(ask.startswith("Move this ticket out of Review")) + self.assertIn("(merged)", ask) + self.assertNotIn("Ask a reviewer", ask) + + def test_the_ask_names_the_requested_reviewers(self): + item = self.item( + pr=[ + { + "number": 257, + "url": "https://github.com/o/r/pull/257", + "status": "OPEN", + "reviewers": ["Tirth Chetan Thakkar", "Rafael Benevides"], + } + ] + ) + ask = pc.decorate_ask(item, "markdown") + self.assertTrue( + ask.startswith( + "Ask Tirth and Rafael to approve or reject " + "PR [#257](https://github.com/o/r/pull/257)" + ), + ask, + ) + + def test_a_closed_pull_request_is_not_what_the_ask_asks_to_review(self): + item = self.item( + pr=[ + {"number": 122, "url": "https://github.com/o/r/pull/122", "status": "MERGED"}, + {"number": 177, "url": "https://github.com/o/r/pull/177", "status": "OPEN"}, + ] + ) + ask = pc.decorate_ask(item, "markdown") + self.assertTrue(ask.startswith("Ask a reviewer")) + self.assertIn("[#177](https://github.com/o/r/pull/177)", ask) + self.assertNotIn("#122", ask) + + +class BuildWiringTest(unittest.TestCase): + """A blocker in Review is not in the queue, and its reviewer is the whole ask.""" + + def args(self, **overrides): + args = mock.Mock( + project="HYPERFLEET", + jira="jira", + min_sp=5, + max_rows=7, + action_after=5, + sp_field="customfield_10028", + sp_field_name="Story Points", + today="2026-11-03", + jobs=1, + no_prs=False, + link_style="markdown", + next_pulse=None, + ) + for name, value in overrides.items(): + setattr(args, name, value) + return args + + def test_a_review_blocker_outside_the_queue_gets_its_reviewers(self): + docs = { + "HYPERFLEET-1534": doc( + "HYPERFLEET-1534", + owner="Phuongnhat Nguyen", + status="Backlog", + changed="2026-08-27", + links=[blocked_by_link("HYPERFLEET-1636")], + ), + "HYPERFLEET-1636": doc( + "HYPERFLEET-1636", + owner="Martin Liptak", + status="Review", + changed="2026-10-27", + ), + } + seen = {} + + def fake_pull_requests(items, jobs): + seen["keys"] = [item["key"] for item in items] + for item in items: + item["pr"] = ( + [ + { + "number": 255, + "url": "https://github.com/o/r/pull/255", + "status": "OPEN", + "reviewers": ["Tirth Chetan Thakkar"], + } + ] + if item["key"] == "HYPERFLEET-1636" + else [] + ) + return {"available": True, "failed": 0, "checked": len(items), "found": 1} + + with mock.patch.object(pc, "active_sprint", return_value={"id": "1", "name": "Sprint 19"}), \ + mock.patch.object(pc, "large_item_keys", return_value=["HYPERFLEET-1534"]), \ + mock.patch.object(pc, "fetch_all", side_effect=lambda keys, *a: {k: docs[k] for k in keys}), \ + mock.patch.object( + pc, + "apply_changelog_signals", + side_effect=lambda items, today, jobs: { + "available": True, + "failed": 0, + "checked": len(items), + "status_dates": 0, + "assignments": 0, + }, + ), \ + mock.patch.object(pc, "apply_pull_requests", side_effect=fake_pull_requests), \ + mock.patch.object(pc, "jira_base_url", return_value="https://example.atlassian.net/browse/"): + data = pc.build(self.args()) + + self.assertIn("HYPERFLEET-1636", seen["keys"]) + ask = next(i for i in data["queue"] if i["key"] == "HYPERFLEET-1534")["ask"] + self.assertIn("Tirth", ask) + self.assertNotIn("Martin", ask) + + def test_skipping_the_lookup_does_not_invent_a_missing_pull_request(self): + docs = { + "HYPERFLEET-1534": doc( + "HYPERFLEET-1534", + owner="Phuongnhat Nguyen", + status="Backlog", + changed="2026-08-27", + links=[blocked_by_link("HYPERFLEET-1636")], + ), + "HYPERFLEET-1636": doc( + "HYPERFLEET-1636", + owner="Martin Liptak", + status="Review", + changed="2026-10-27", + ), + } + + with mock.patch.object(pc, "active_sprint", return_value={"id": "1", "name": "Sprint 19"}), \ + mock.patch.object(pc, "large_item_keys", return_value=["HYPERFLEET-1534"]), \ + mock.patch.object(pc, "fetch_all", side_effect=lambda keys, *a: {k: docs[k] for k in keys}), \ + mock.patch.object( + pc, + "apply_changelog_signals", + side_effect=lambda items, today, jobs: { + "available": True, + "failed": 0, + "checked": len(items), + "status_dates": 0, + "assignments": 0, + }, + ), \ + mock.patch.object( + pc, "apply_pull_requests", side_effect=AssertionError("must not be read") + ), \ + mock.patch.object(pc, "jira_base_url", return_value="https://example.atlassian.net/browse/"): + data = pc.build(self.args(no_prs=True)) + + ask = next(i for i in data["queue"] if i["key"] == "HYPERFLEET-1534")["ask"] + self.assertIn("a reviewer to approve or reject", ask.lower()) + self.assertNotIn("Attach", ask) + self.assertNotIn("Martin", ask) + + def test_an_unavailable_lookup_does_not_invent_a_missing_pull_request(self): + docs = { + "HYPERFLEET-1534": doc( + "HYPERFLEET-1534", + owner="Phuongnhat Nguyen", + status="Backlog", + changed="2026-08-27", + links=[blocked_by_link("HYPERFLEET-1636")], + ), + "HYPERFLEET-1636": doc( + "HYPERFLEET-1636", + owner="Martin Liptak", + status="Review", + changed="2026-10-27", + ), + } + + with mock.patch.object(pc, "active_sprint", return_value={"id": "1", "name": "Sprint 19"}), \ + mock.patch.object(pc, "large_item_keys", return_value=["HYPERFLEET-1534"]), \ + mock.patch.object(pc, "fetch_all", side_effect=lambda keys, *a: {k: docs[k] for k in keys}), \ + mock.patch.object( + pc, + "apply_changelog_signals", + side_effect=lambda items, today, jobs: { + "available": True, + "failed": 0, + "checked": len(items), + "status_dates": 0, + "assignments": 0, + }, + ), \ + mock.patch.object(jc, "jira_api", return_value=None), \ + mock.patch.object(pc, "jira_base_url", return_value="https://example.atlassian.net/browse/"): + data = pc.build(self.args()) + + ask = next(i for i in data["queue"] if i["key"] == "HYPERFLEET-1534")["ask"] + self.assertFalse(data["pr_signal"]["available"]) + self.assertIn("a reviewer to approve or reject", ask.lower()) + self.assertNotIn("Attach", ask) + self.assertNotIn("Martin", ask) + + +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](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() + 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](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): + 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) + + def test_a_failed_issue_read_is_reported(self): + data = self.data() + data["fetch_signal"] = {"failed": 2, "keys": ["HYPERFLEET-1", "HYPERFLEET-2"]} + self.assertIn("2 issue reads failed", pc.render_text(data)) + + 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_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"] = { + "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/" + + 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") + + +class LargeItemQueryTest(unittest.TestCase): + def test_done_is_filtered_by_category_not_by_status_name(self): + with mock.patch.object(pc, "search_keys", return_value=["HYPERFLEET-1"]) as fake: + keys = pc.large_item_keys( + "HYPERFLEET", "66537", 5, "Story Points", "jira" + ) + jql = fake.call_args.args[0] + 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, "search_keys", return_value=[]) as fake: + pc.large_item_keys("HYPERFLEET", "66537", 5, "Story Points", "jira") + jql = fake.call_args.args[0] + self.assertIn("sprint = 66537", jql) + self.assertNotIn("openSprints()", jql) + + def test_the_lookup_pages_instead_of_truncating_at_100(self): + # `jira issue list` caps at 100; search_keys moves the JQL window. + with mock.patch.object(pc, "search_keys", return_value=[]) as fake: + pc.large_item_keys("HYPERFLEET", "66537", 5, "Story Points", "jira") + self.assertEqual(fake.call_args.args[1:], ("HYPERFLEET", "jira")) + + +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 new file mode 100644 index 0000000..607e8b1 --- /dev/null +++ b/hyperfleet-jira/tests/test_sprint_status.py @@ -0,0 +1,1308 @@ +"""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 io +import json +import os +import sys +import tempfile +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 jira_common as jc # noqa: E402 +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", + sprints=(), +): + 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": ( + changed if "T" in changed else f"{changed}T10:00:00.000+0000" + ), + "comment": {"comments": list(comments)}, + "issuelinks": list(links), + "customfield_10020": list(sprints) or None, + }, + } + + +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(jc, "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( + 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"]) + self.assertEqual(fake.call_count, 1) + + +class FetchAllTest(unittest.TestCase): + """One unreadable key must not abort a report about the rest.""" + + def test_an_unreadable_key_does_not_abort_the_others(self): + failures = {} + + def fake_issue(key, project, binary): + if key == "HYPERFLEET-2": + raise jc.JiraError("no permission") + return {"key": key} + + with mock.patch.object(jc, "fetch_issue", side_effect=fake_issue): + docs = jc.fetch_all( + ["HYPERFLEET-1", "HYPERFLEET-2", "HYPERFLEET-3"], + "HYPERFLEET", + "jira", + 2, + failures, + ) + + self.assertEqual(sorted(docs), ["HYPERFLEET-1", "HYPERFLEET-3"]) + self.assertEqual(sorted(failures), ["HYPERFLEET-2"]) + + def test_an_unreadable_blocker_stays_open_with_an_unknown_status(self): + items = [{"key": "HYPERFLEET-1", "blocked_by": ["HYPERFLEET-2"]}] + + def fake_issue(key, project, binary): + raise jc.JiraError("no permission") + + with mock.patch.object(jc, "fetch_issue", side_effect=fake_issue): + ss.resolve_blockers( + items, {"HYPERFLEET-1": doc("HYPERFLEET-1")}, "HYPERFLEET", "jira", 1, {} + ) + + # Unknown is not Done: the blocker stays visible, with no status to trust. + self.assertEqual(items[0]["open_blockers"], ["HYPERFLEET-2"]) + self.assertEqual(items[0]["blocker_detail"][0]["status"], "?") + + +class DescribeTest(unittest.TestCase): + def test_status_category_is_read_not_status_name(self): + 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("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, + ) + self.assertEqual(described["days_without_movement"], 30) + self.assertIsNone(described["last_comment"]) + + 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, + ) + 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 = jc.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(jc, "jira_api", return_value=("https://x", "auth")), \ + mock.patch.object( + jc, "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(jc, "jira_api", return_value=("https://x", "auth")), \ + mock.patch.object( + 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( + jc.status_change_counts({"fromString": "New", "toString": "Backlog"}) + ) + self.assertTrue( + jc.status_change_counts({"fromString": "Backlog", "toString": "In Progress"}) + ) + self.assertTrue( + 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(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) + + +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") + + +class PullRequestTest(unittest.TestCase): + """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, key="HYPERFLEET-104"): + return [ + {"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): + owned = jc.pull_requests_from(self.payload(), "HYPERFLEET-104") + self.assertEqual([pr["number"] for pr in owned], [104, 99]) + + def test_the_same_number_in_two_repositories_is_two_pull_requests(self): + payload = [ + { + "object": { + "url": "https://github.com/o/hyperfleet-api/pull/120", + "title": "HYPERFLEET-104 - fix: api", + } + }, + { + "object": { + "url": "https://github.com/o/hyperfleet-infra/pull/120", + "title": "HYPERFLEET-104 - fix: infra", + } + }, + ] + owned = jc.pull_requests_from(payload, "HYPERFLEET-104") + self.assertEqual( + sorted(pr["url"] for pr in owned), + [ + "https://github.com/o/hyperfleet-api/pull/120", + "https://github.com/o/hyperfleet-infra/pull/120", + ], + ) + + 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"), []) + self.assertEqual( + jc.pull_requests_from(payload, "HYPERFLEET-1636"), + [{"number": 255, "url": "https://github.com/o/r/pull/255"}], + ) + + 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_nobodys_pull_request(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): + owned = jc.pull_requests_from( + [ + {"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 owned], [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"], []) + + def test_an_unread_item_is_marked_unknown_not_empty(self): + items = [{"key": "HYPERFLEET-1", "status": "Review"}] + with mock.patch.object(jc, "jira_api", return_value=None): + jc.apply_pull_requests(items, 2) + # The caller must not read `pr: []` as "this ticket has no pull request". + self.assertTrue(items[0]["pr_unknown"]) + + def test_a_failed_item_is_marked_unknown_while_a_read_item_is_not(self): + items = [ + {"key": "HYPERFLEET-1", "status": "Review"}, + {"key": "HYPERFLEET-2", "status": "Review"}, + ] + + def read(key, issue_id, api): + if key == "HYPERFLEET-1": + return [], "HYPERFLEET-1: URLError" + return [{"number": 7, "url": "https://github.com/o/r/pull/7"}], None + + with mock.patch.object(jc, "jira_api", return_value=("https://example", "auth")), \ + mock.patch.object(jc, "read_pull_requests", side_effect=read): + jc.apply_pull_requests(items, 1) + + self.assertTrue(items[0]["pr_unknown"]) + self.assertFalse(items[1]["pr_unknown"]) + self.assertEqual(items[1]["pr"][0]["number"], 7) + + +class ApplicationTypesTest(unittest.TestCase): + """A missing branch is "no pull request"; a wrong type is a broken answer.""" + + def test_a_missing_branch_is_empty(self): + for summary in ({}, {"summary": {}}, {"summary": {"pullrequest": {}}}): + self.assertEqual(jc.application_types(summary), [], summary) + + def test_a_non_object_branch_is_malformed(self): + for summary in ( + [], + "a string", + {"summary": "a string"}, + {"summary": {"pullrequest": []}}, + {"summary": {"pullrequest": {"byInstanceType": ["GitHub"]}}}, + ): + self.assertIsNone(jc.application_types(summary), summary) + + def test_the_instance_ids_are_returned(self): + summary = { + "summary": { + "pullrequest": { + "byInstanceType": {"GitHub": {"count": 1}, "Bitbucket": {"count": 0}} + } + } + } + self.assertEqual( + sorted(jc.application_types(summary)), ["Bitbucket", "GitHub"] + ) + + +class DevelopmentPanelTest(unittest.TestCase): + """The GitHub app reports through `dev-status`; remote links are the smaller half.""" + + api = ("https://example.atlassian.net", "auth") + app = "oAuth-com.github.integration.production" + + 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 pr(self, number, title, status="OPEN", repo="hyperfleet-api"): + return { + "id": f"#{number}", + "name": title, + "status": status, + "url": f"https://github.com/openshift-hyperfleet/{repo}/pull/{number}", + "lastUpdate": "2026-11-02T10:00:00.000+0000", + } + + def patch(self, panel=(), links=()): + """Route each request by URL: summary, detail, or remote links.""" + urls = [] + + def open_(request): + url = request.full_url + urls.append(url) + if "issue/summary" in url: + return self.Response( + {"summary": {"pullrequest": {"byInstanceType": {self.app: {"count": 1}}}}} + ) + if "issue/detail" in url: + return self.Response({"detail": [{"pullRequests": list(panel)}]}) + if "remotelink" in url: + return self.Response(list(links)) + raise AssertionError(f"unexpected url {url}") + + return mock.patch.object(jc, "open_changelog", side_effect=open_), urls + + def read(self, key="HYPERFLEET-1669", panel=(), links=()): + patcher, urls = self.patch(panel, links) + with patcher: + return jc.read_pull_requests(key, "7126783", self.api), urls + + def test_the_application_type_is_read_from_the_summary(self): + _, urls = self.read(panel=[self.pr(416, "HYPERFLEET-1669 - fix: claims")]) + detail = [url for url in urls if "issue/detail" in url] + self.assertTrue(detail) + self.assertIn(f"applicationType={self.app}", detail[0]) + + def test_a_pull_request_titled_for_the_ticket_keeps_its_state(self): + (prs, error), _ = self.read( + panel=[self.pr(416, "HYPERFLEET-1669 - fix: claims", status="MERGED")] + ) + self.assertIsNone(error) + self.assertEqual([pr["number"] for pr in prs], [416]) + self.assertEqual(prs[0]["status"], "MERGED") + + def test_the_requested_reviewers_ride_along(self): + pr = self.pr(416, "HYPERFLEET-1669 - fix: claims") + pr["author"] = {"name": "Leonardo Dorneles"} + pr["reviewers"] = [ + {"name": "Michaela Parilova", "approved": False}, + {"name": "User ", "approved": False}, + {"name": "Leonardo Dorneles", "approved": False}, + {"name": "Tirth Chetan Thakkar", "approved": True}, + ] + (prs, error), _ = self.read(panel=[pr]) + self.assertIsNone(error) + # The author is not asked to approve their own diff, an approved reviewer + # has already decided, and `User ` is what the panel shows for an account + # it cannot resolve. + self.assertEqual(prs[0]["reviewers"], ["Michaela Parilova"]) + + def test_a_pull_request_titled_for_another_ticket_does_not_appear(self): + (prs, _), _ = self.read(panel=[self.pr(255, "HYPERFLEET-1636 - docs: contract")]) + self.assertEqual(prs, []) + + def test_a_link_that_only_exists_as_a_remote_link_is_kept(self): + links = [ + {"object": {"url": "https://github.com/openshift-hyperfleet/architecture/pull/255", + "title": "openshift-hyperfleet/architecture#255: HYPERFLEET-1669 - docs"}} + ] + (prs, _), _ = self.read(panel=[], links=links) + self.assertEqual([pr["number"] for pr in prs], [255]) + # A hand-attached link carries no reviewer list: unknown, not empty. + self.assertNotIn("reviewers", prs[0]) + + def test_the_same_pull_request_from_both_sources_is_listed_once_with_its_state(self): + url = "https://github.com/openshift-hyperfleet/hyperfleet-api/pull/416" + links = [{"object": {"url": url, "title": "HYPERFLEET-1669 - fix: claims"}}] + (prs, _), _ = self.read( + panel=[self.pr(416, "HYPERFLEET-1669 - fix: claims", status="MERGED")], + links=links, + ) + self.assertEqual(len(prs), 1) + self.assertEqual(prs[0]["status"], "MERGED") + + def test_a_remote_link_failure_still_returns_the_panel_pull_requests(self): + def open_(request): + url = request.full_url + if "remotelink" in url: + raise jc.urllib.error.URLError("boom") + if "issue/summary" in url: + return self.Response( + {"summary": {"pullrequest": {"byInstanceType": {self.app: {"count": 1}}}}} + ) + if "issue/detail" in url: + return self.Response( + {"detail": [{"pullRequests": [self.pr(416, "HYPERFLEET-1669 - fix: claims")]}]} + ) + raise AssertionError(f"unexpected url {url}") + + with mock.patch.object(jc, "open_changelog", side_effect=open_): + prs, error = jc.read_pull_requests("HYPERFLEET-1669", "7126783", self.api) + + # Half the list is better than none, as long as the signal says "partial". + self.assertEqual([pr["number"] for pr in prs], [416]) + self.assertIn("URLError", error) + + def test_one_failing_application_type_keeps_the_other_types_pull_requests(self): + other = "GitHub" + + def open_(request): + url = request.full_url + if "issue/summary" in url: + return self.Response( + { + "summary": { + "pullrequest": { + "byInstanceType": {self.app: {"count": 1}, other: {"count": 1}} + } + } + } + ) + if "issue/detail" in url: + # The summary names two apps; the second one fails. + if f"applicationType={other}" in url: + raise jc.urllib.error.URLError("boom") + return self.Response( + {"detail": [{"pullRequests": [self.pr(416, "HYPERFLEET-1669 - fix: claims")]}]} + ) + if "remotelink" in url: + return self.Response([]) + raise AssertionError(f"unexpected url {url}") + + with mock.patch.object(jc, "open_changelog", side_effect=open_): + prs, error = jc.read_pull_requests("HYPERFLEET-1669", "7126783", self.api) + + # One app failing is partial, not empty: the other app's pull request stays. + self.assertEqual([pr["number"] for pr in prs], [416]) + self.assertIn("URLError", error) + + def test_a_malformed_detail_response_is_a_partial_read(self): + def open_(request): + url = request.full_url + if "issue/summary" in url: + return self.Response( + {"summary": {"pullrequest": {"byInstanceType": {self.app: {"count": 1}}}}} + ) + if "issue/detail" in url: + # Valid JSON, wrong shape: `.get` on this would abort the report. + return self.Response([{"pullRequests": []}]) + if "remotelink" in url: + return self.Response( + [ + { + "object": { + "url": "https://github.com/openshift-hyperfleet/architecture/pull/255", + "title": "HYPERFLEET-1669 - docs: contract", + } + } + ] + ) + raise AssertionError(f"unexpected url {url}") + + with mock.patch.object(jc, "open_changelog", side_effect=open_): + prs, error = jc.read_pull_requests("HYPERFLEET-1669", "7126783", self.api) + + # The remote link survives, and the bad panel answer is reported, not swallowed. + self.assertEqual([pr["number"] for pr in prs], [255]) + self.assertIn("MalformedResponse", error) + + def test_a_summary_without_an_application_branch_is_no_pull_request(self): + def open_(request): + url = request.full_url + if "issue/summary" in url: + # What Jira answers for an issue no app has touched. + return self.Response({"summary": {}}) + if "remotelink" in url: + return self.Response( + [ + { + "object": { + "url": "https://github.com/openshift-hyperfleet/architecture/pull/255", + "title": "HYPERFLEET-1669 - docs: contract", + } + } + ] + ) + raise AssertionError(f"unexpected url {url}") + + with mock.patch.object(jc, "open_changelog", side_effect=open_): + prs, error = jc.read_pull_requests("HYPERFLEET-1669", "7126783", self.api) + + # "No app reported one" is a fact, not a failed read: the link is kept and + # the signal stays complete, so the ask can still say "attach the PR". + self.assertEqual([pr["number"] for pr in prs], [255]) + self.assertIsNone(error) + + def test_a_malformed_summary_is_a_partial_read(self): + def open_(request): + url = request.full_url + if "issue/summary" in url: + # Valid JSON, wrong shape: `.get` on this would abort the report. + return self.Response([{"summary": {}}]) + if "remotelink" in url: + return self.Response( + [ + { + "object": { + "url": "https://github.com/openshift-hyperfleet/architecture/pull/255", + "title": "HYPERFLEET-1669 - docs: contract", + } + } + ] + ) + raise AssertionError(f"unexpected url {url}") + + with mock.patch.object(jc, "open_changelog", side_effect=open_): + prs, error = jc.read_pull_requests("HYPERFLEET-1669", "7126783", self.api) + + self.assertEqual([pr["number"] for pr in prs], [255]) + self.assertIn("MalformedResponse", error) + + def test_a_panel_failure_still_returns_the_remote_link_pull_requests(self): + url = "https://github.com/openshift-hyperfleet/architecture/pull/255" + links = [{"object": {"url": url, "title": "HYPERFLEET-1669 - docs: contract"}}] + + def open_(request): + full_url = request.full_url + if "remotelink" in full_url: + return self.Response(links) + raise jc.urllib.error.URLError("boom") + + with mock.patch.object(jc, "open_changelog", side_effect=open_): + prs, error = jc.read_pull_requests("HYPERFLEET-1669", "7126783", self.api) + + self.assertEqual([pr["number"] for pr in prs], [255]) + self.assertIn("URLError", error) + + def test_a_merged_state_is_rendered_and_open_is_not(self): + merged = {"number": 181, "url": "https://github.com/o/r/pull/181", "status": "MERGED"} + opened = {"number": 177, "url": "https://github.com/o/r/pull/177", "status": "OPEN"} + self.assertTrue(jc.pr_ref(merged, "markdown").endswith("(merged)")) + self.assertEqual(jc.pr_ref(opened, "markdown"), "[#177](https://github.com/o/r/pull/177)") + + +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_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} + 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_failed_issue_read_is_named(self): + data = self.data() + data["fetch_signal"] = {"failed": 2, "keys": ["HYPERFLEET-1", "HYPERFLEET-2"]} + self.assertIn("signal: partial - 2 issue reads failed", 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(jc, "jira_api", return_value=self.api), \ + mock.patch.object( + jc, "changelog_dates", + side_effect=jc.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(jc, "jira_api", return_value=self.api), \ + mock.patch.object( + jc, "changelog_dates", side_effect=jc.ChangelogUnavailable("boom") + ): + ss.apply_changelog_signals([subject], TODAY, 1) + self.assertEqual(subject["days_without_movement"], 13) + 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(jc.Path, "home", return_value=Path(self.tmp.name)), \ + mock.patch.dict(os.environ, {"JIRA_API_TOKEN": "token"}): + return jc.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(jc, "open_changelog", side_effect=error) + else: + patcher = mock.patch.object( + jc, "open_changelog", return_value=self.Response(payload) + ) + with patcher: + return jc.changelog_dates("HYPERFLEET-1", "acc-1", self.api) + + def test_a_network_error_is_counted(self): + with self.assertRaises(jc.ChangelogUnavailable): + self.call(error=jc.urllib.error.URLError("401 Unauthorized")) + + def test_a_truncated_response_is_counted(self): + with self.assertRaises(jc.ChangelogUnavailable): + 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") + with self.assertRaises(jc.ChangelogUnavailable): + self.call(error=error) + + def test_a_capped_changelog_is_counted(self): + with self.assertRaises(jc.ChangelogUnavailable): + self.call(payload={"changelog": {"total": 150, "histories": []}}) + + def test_a_non_object_response_is_counted(self): + with self.assertRaises(jc.ChangelogUnavailable): + self.call(payload=["not", "a", "dict"]) + + def test_a_non_object_changelog_is_counted(self): + with self.assertRaises(jc.ChangelogUnavailable): + self.call(payload={"changelog": ["not", "a", "dict"]}) + + def test_histories_that_are_not_a_list_are_counted(self): + with self.assertRaises(jc.ChangelogUnavailable): + self.call(payload={"changelog": {"histories": {"created": "2026-10-30"}}}) + + def test_an_entry_that_is_not_an_object_is_counted(self): + with self.assertRaises(jc.ChangelogUnavailable): + self.call(payload={"changelog": {"histories": ["not an entry"]}}) + + def test_movement_without_a_date_is_counted(self): + payload = { + "changelog": { + "histories": [ + { + "items": [ + { + "field": "status", + "fromString": "In Progress", + "toString": "Review", + } + ] + } + ] + } + } + with self.assertRaises(jc.ChangelogUnavailable): + self.call(payload=payload) + + def test_movement_with_an_unreadable_date_is_counted(self): + payload = { + "changelog": { + "histories": [ + { + "created": "yesterday", + "items": [ + { + "field": "status", + "fromString": "In Progress", + "toString": "Review", + } + ], + } + ] + } + } + with self.assertRaises(jc.ChangelogUnavailable): + self.call(payload=payload) + + def test_a_status_value_that_is_not_text_is_counted(self): + payload = { + "changelog": { + "histories": [ + { + "created": "2026-10-30T10:00:00.000+0000", + "items": [ + {"field": "status", "fromString": 1, "toString": "Review"} + ], + } + ] + } + } + with self.assertRaises(jc.ChangelogUnavailable): + self.call(payload=payload) + + 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 = jc.NoRedirect() + with self.assertRaises(jc.urllib.error.HTTPError) as caught: + handler.redirect_request( + jc.urllib.request.Request("https://a.example"), + None, + 302, + "Found", + {}, + "https://b.example", + ) + + +class ProjectArgumentTest(unittest.TestCase): + def test_a_project_key_is_accepted(self): + self.assertEqual(jc.project_key("HYPERFLEET"), "HYPERFLEET") + + def test_jql_is_not_a_project_key(self): + with self.assertRaises(jc.argparse.ArgumentTypeError): + jc.project_key("HF OR project = SECRET") + + def test_a_cli_date_must_be_iso(self): + self.assertEqual(jc.iso_date("2026-11-03"), "2026-11-03") + for bad in ("03/11/2026", "2026-11-03T00:00:00", "20261103"): + with self.assertRaises(jc.argparse.ArgumentTypeError): + jc.iso_date(bad) + + def test_a_thread_count_must_be_positive(self): + self.assertEqual(jc.positive_int("8"), 8) + for bad in ("0", "-1", "x"): + with self.assertRaises(jc.argparse.ArgumentTypeError): + jc.positive_int(bad) + + +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_before_the_recorded_close_counts_even_past_the_plan(self): + # Sprint 18 was planned to 2026-11-01 and closed on 2026-11-02: a point + # closed in between belongs to that sprint, not to the next one. + record = { + "id": 66536, + "name": "Hyperfleet Sprint 18", + "state": "closed", + "startDate": "2026-10-12T08:27:25.346Z", + "endDate": "2026-11-01T23:00:00.000Z", + "completeDate": "2026-11-02T08:49:07.513Z", + } + baseline = self.run_baseline( + [ + doc( + "HYPERFLEET-1", + sp=5, + status="Closed", + category="Done", + changed="2026-11-02T07:00:00.000+0000", + sprints=[record], + ) + ] + ) + self.assertEqual(baseline["delivered_sp"], 5) + self.assertEqual(baseline["end"], "2026-11-02") + self.assertEqual(baseline["days"], 22) + + def test_work_closed_after_the_close_on_the_close_day_is_not_delivered(self): + # Sprint 18 closed at 08:49; HYPERFLEET-1731 went Done at 14:11 that day, + # which is next sprint's delivery, not this one's. + record = { + "id": 66536, + "name": "Hyperfleet Sprint 18", + "state": "closed", + "startDate": "2026-10-12T08:27:25.346Z", + "endDate": "2026-11-01T23:00:00.000Z", + "completeDate": "2026-11-02T08:49:07.513Z", + } + baseline = self.run_baseline( + [ + doc( + "HYPERFLEET-1", + sp=5, + status="Closed", + category="Done", + changed="2026-11-02T14:11:19.869+0000", + sprints=[record], + ) + ] + ) + self.assertEqual(baseline["delivered_sp"], 0) + self.assertEqual(baseline["committed_sp"], 5) + + def test_the_planned_end_is_the_fallback_when_no_issue_reports_a_close(self): + baseline = self.run_baseline( + [doc("HYPERFLEET-1", sp=5, status="Closed", category="Done", changed="2026-10-25")] + ) + self.assertEqual(baseline["end"], "2026-10-25") + self.assertEqual(baseline["days"], 14) + + 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()