Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first
CI / tests (pull_request) Successful in 2m8s

This commit is contained in:
2026-11-16 02:41:43 +01:00
parent 9d685c52b3
commit 2db4759c2a
15 changed files with 361 additions and 71 deletions
+85 -18
View File
@@ -2,7 +2,7 @@
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a person filed holds none, and reads as an item without scores.
`add` files an item as a new child issue, marked with FILED_BY, and `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
`add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
import base64
import dataclasses
import pathlib
@@ -13,10 +13,11 @@ from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from release_plan.todo_table import BLOCKED_BY, EXEMPTIONS, is_exempt, Item, MOVES, parse_ids, parse_moves, parse_scores, SHAPE
from plan_store.markdown_edits import bold_cell, plain, unfit_text
from plan_store.stores import cells, Plan, Written
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA
from failure import Failure
from rest_client import json_request
from release_plan.release import parsed, Release, tagged
from release_plan import ranking
from rest_client.env_file import read_env
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
@@ -55,6 +56,11 @@ ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
class ReadsScoring(typing.Protocol):
def read(self) -> ranking.Scoring | Failure:
"""The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give."""
def http_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
@@ -95,6 +101,8 @@ class JiraPlan:
to_adf: ToAdf = markdown_to_adf
# How a finished item moves; None where the config doesn't say, and then `finish` is a Failure.
finish_by: Finish | None = None
# None where the config states no formula and bar, and then `add` is a Failure.
scoring: ReadsScoring | None = None
@property
def label(self) -> str:
@@ -115,12 +123,20 @@ class JiraPlan:
return next((issue for issue in issues if isinstance(issue, Failure)), None) or plan_of([issue for issue in issues if isinstance(issue, Issue)], self.epic, self.to_markdown)
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
"""Files the item as a child issue, which Jira ranks last in the backlog. No bar applies and the goals file isn't read, since a plan in Jira has no place for a formula or a bar yet (todo.md's item 384).
"""Files the item as a child issue, where it scores at the config's bar or above or is exempt, and ranks it as `placing` says.
Jira takes the links after the issue. A link it refuses leaves the issue filed, so the write counts as landed, and a note names each link to make by hand."""
Jira takes the links and the rank after the issue. One it refuses leaves the issue filed, so the write counts as landed, and a note says what to do by hand."""
filing = filing_of(fields, detail, self.epic)
if isinstance(filing, Failure):
return filing
if self.scoring is None:
return Failure(f"the config states no formula and bar to score the item by: set `{JIRA_SCORE_FORMULA}` and `{JIRA_SCORE_BAR}`, as `project-config --help` shows")
scoring = self.scoring.read()
if isinstance(scoring, Failure):
return Failure(f"cannot score the item to file: {scoring.reason}")
value = filed_score(filing.item, scoring)
if isinstance(value, Failure):
return value
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
@@ -133,8 +149,14 @@ class JiraPlan:
version = self.fix_version(filing.release, authorization)
if isinstance(version, Failure):
return version
if filing.blockers and (missing := self.missing_blocker(filing.blockers, authorization)):
return missing
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
# `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read.
if missing := next((blocker for blocker in filing.blockers if blocker not in held), None):
return Failure(f"{self.label} holds no item {number(missing)} to be blocked by")
before = placing(answered, filing.item, value, scoring)
created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]})
if isinstance(created, Failure):
return Failure(f"cannot file the item under {self.epic.key}: {created.reason}; {PERHAPS_FILED.format(epic=self.epic.key)}")
@@ -147,8 +169,21 @@ class JiraPlan:
linked = self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
if isinstance(linked, Failure):
notes.append(f"filed {key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
if isinstance(before, Failure):
notes.append(f"filed {key}, but cannot rank it: {before.reason}; rank it in Jira")
elif before is not None and (refused := self.rank_refusal(key, before, authorization)):
notes.append(f"filed {key}, but cannot rank it before {before}: {refused}; rank it in Jira")
return Written(number(key), tuple(notes))
def rank_refusal(self, key: str, before: str, authorization: str) -> str | None:
"""Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors."""
answer = self.http("PUT", f"{self.epic.site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before})
if isinstance(answer, Failure):
return answer.reason
entries = answer.get("entries") if isinstance(answer, dict) else None
refused = [entry for entry in entries if isinstance(entry, dict) and entry.get("status") != 200] if isinstance(entries, list) else []
return "; ".join(str(error) for entry in refused for error in entry.get("errors") or [f"Jira answered {entry.get('status')}"]) or None
def fix_version(self, release: str, authorization: str) -> str | Failure:
"""The name of the Jira project's Fix Version for release, which a project may spell with a leading v, as `earliest_release` reads it."""
project = project_of(self.epic.key)
@@ -158,14 +193,6 @@ class JiraPlan:
names = {name for version in versions if isinstance(version, dict) and isinstance(name := version.get("name"), str)} if isinstance(versions, list) else set()
return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or name a release it has")
def missing_blocker(self, blockers: tuple[str, ...], authorization: str) -> Failure | None:
"""A Failure naming the first of blockers that is no open child of the epic. `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read."""
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
return next((Failure(f"{self.label} holds no item {number(blocker)} to be blocked by") for blocker in blockers if blocker not in held), None)
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
"""Sets the fields and the detail in one request, so Jira takes all of the edit or none, and then posts comment on the issue. `revision_of` says what an edit may set.
@@ -243,6 +270,8 @@ class Filing:
scores: dict[str, typing.Any]
# The key of each issue the item is blocked by.
blockers: tuple[str, ...]
# The item as ranking scores it, under the ID 0, since Jira numbers it once filed.
item: Item
def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failure:
@@ -254,15 +283,16 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu
if unfit := unfit_text(summary, detail):
return unfit
release = named.get("Release", "")
if parsed(release) is None:
version = parsed(release)
if version is None:
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
# Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet.
levels = parse_scores("to file", named, SHAPE.score_columns)
if isinstance(levels, Failure):
return levels
moves, exempt = named.get(MOVES, ""), named.get("Exempt", "")
if isinstance(unfit_moves := parse_moves("to file", moves), Failure):
return unfit_moves
if isinstance(parsed_moves := parse_moves("to file", moves), Failure):
return parsed_moves
if not is_exempt(exempt):
return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
blockers = parse_ids(named.get(BLOCKED_BY, ""))
@@ -273,7 +303,44 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu
if exempt == SECURITY:
issue_fields["labels"] = [SECURITY]
value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]}
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers))
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers), Item(0, version, exempt, summary, levels, parsed_moves, blockers))
def filed_score(item: Item, scoring: ranking.Scoring) -> float | Failure:
"""The item's score, or why it may not be filed: it lacks a score the formula may use, names a goal it may not, or scores under the bar without being exempt."""
if missing := next((name for name in SET_SCORES if name not in item.scores), None):
return Failure(f"the item to file has no {missing}: score it on {', '.join(SET_SCORES[:-1])} and {SET_SCORES[-1]}")
value = ranking.item_score(item, scoring, "the item to file")
if not isinstance(value, Failure) and not item.exempt and round(value, 1) < scoring.bar:
return Failure(f"the item to file scores {value:.1f}, under the bar {scoring.bar:g}; don't file it, or mark it with a reason the bar doesn't apply")
return value
def placing(answered: list[object], new: Item, value: float, scoring: ranking.Scoring) -> str | None | Failure:
"""The key of the issue to rank the new item, which scores value, just before; None where it stays last, where Jira files it. answered is the epic's open children in backlog order.
Only the issues the loop filed count, so the team's rank of every other issue stays as it is. A security finding goes before the first of them that isn't one, and any other item before the first that isn't one and scores lower, as todo.md ranks its items."""
for raw in answered:
issue = issue_of(raw)
if isinstance(issue, Failure):
return issue
if not isinstance(issue.scores, dict) or issue.scores.get(FILED_BY[0]) != FILED_BY[1]:
continue
scored = scores(issue.key, issue.scores)
if isinstance(scored, Failure):
return scored
levels, moves, exempt = scored
if exempt == SECURITY:
continue
if new.exempt == SECURITY:
return issue.key
if missing := next((name for name in SET_SCORES if name not in levels), None):
return Failure(f"{issue.key} holds no {missing}")
# Release, tagline and blockers don't change a score.
other = ranking.item_score(dataclasses.replace(new, id=issue.number, exempt=exempt, scores=levels, moves=moves), scoring, issue.key)
if isinstance(other, Failure) or other < value:
return other if isinstance(other, Failure) else issue.key
return None
@dataclasses.dataclass(frozen=True)