Start a do-epic chunk's issue in Jira: assigned, moved by a start transition and added to a board's active sprint

This commit is contained in:
Lilleman
2026-11-20 17:23:58 +01:00
parent 00b87e3fb9
commit 653fcbe3f1
13 changed files with 358 additions and 21 deletions
+1
View File
@@ -158,6 +158,7 @@ The last line prints each setting's path once the config is complete.
- `config.toml` fits do-epic to a team whose own automation moves issues, such as a CI job that moves an issue when its pull request merges. Two settings do:
- `jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks, and `--status` names the statuses beside each blocker. A status Jira counts as done always does both. The release reviews, which are the epic's last chunk, still wait until Jira counts every issue done: run `do-epic <EPIC-KEY>` then, to start them.
- `jira-automation-moves-issues = true` keeps do-epic from moving the issue of a finished chunk in a repo: the automation moves it, and do-epic waits for that move before it starts what the issue blocks. An issue without a repo has no pull request, so do-epic still moves it, with `jira-finish-transition`. The setting needs `jira-unblocking-statuses`, which names the status the automation gives an issue whose pull request merged.
- `config.toml` shows a team's board that a chunk has started. A starting chunk always assigns its issue to the account do-epic works as, unless someone else holds it. `jira-start-transition` names the workflow transition that then moves the issue, such as `"In Progress"`; an issue whose work has started already keeps its status. `jira-sprint-board` is the ID of the board whose active sprint the issue joins, such as `6`. Without a setting, do-epic doesn't make that move.
- `config.toml` may set `jira-finding-type`, the issue type do-epic files a finding as, and `jira-review-type`, the one it files a repo's release review as, such as `"Feature"` and `"Chore"`. Both are Task where left out. do-epic doesn't file anything where the Jira project lacks the type, and says which types it has.
- `config.toml` may set `sub-task-summary`, which shapes the summary of each sub-task do-epic files for an issue that changes several repos, such as `sub-task-summary = "{label}: {Summary}"`. `{label}` is the team's label for the repo, else the repo's name, and `{Summary}` is the issue's summary with a capital first letter. It must hold `{Summary}`. Without it a summary is `[<repo>] <the issue's summary>`.
- `config.toml` may end with a `[label-repos]` table, for a team that already labels its issues by repo. Give it one line for each such label: the label, then the repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. Where the label is the repo's name, map the name to itself, as in `core-4 = "core-4"`. Where several lines name one repo, do-epic writes the label of the first. Write every other setting above the table.
+12 -4
View File
@@ -76,6 +76,15 @@ def offer_of(raw: object) -> tuple[str, str, str, str] | None:
return (id_, name, status, key) if isinstance(id_, str) and isinstance(name, str) and isinstance(status, str) and isinstance(key, str) else None
def offers_of(offered: object, key: str) -> list[tuple[str, str, str, str]] | Failure:
"""Each transition in Jira's answer about those the issue named key has from its present status, as offer_of answers one."""
raw = offered.get("transitions") if isinstance(offered, dict) else None
found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else []
if not isinstance(raw, list) or len(found) != len(raw):
return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")
return found
def status_category(issue: object) -> str | Failure:
"""The key of the category of the status in Jira's answer about one issue, or how the answer is not in the shape Jira documents."""
fields = issue.get("fields") if isinstance(issue, dict) else None
@@ -101,10 +110,9 @@ def move_refusal(site: str, key: str, transition: str, finish: Finish, authoriza
def transition_of(offered: object, key: str, finish: Finish) -> str | Failure:
"""The ID of the transition finish names, among those Jira offered for the issue named key, which are the ones its present status has; or why none of them finishes the item."""
raw = offered.get("transitions") if isinstance(offered, dict) else None
found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else []
if not isinstance(raw, list) or len(found) != len(raw):
return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")
found = offers_of(offered, key)
if isinstance(found, Failure):
return found
named = [each for each in found if each[1] == finish.transition]
if not named:
others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found)
+21 -1
View File
@@ -1,4 +1,4 @@
"""What every backend of an epic's plan must hold, as tests. A backend's test case inherits EpicStoreContract and unittest.TestCase, and builds an epic with no issues in new_store. Its comments_on reads an issue's comments. Its assign, close, person_files, score and block change the tracker as a person or the plan store would."""
"""What every backend of an epic's plan must hold, as tests. A backend's test case inherits EpicStoreContract and unittest.TestCase, and builds an epic with no issues in new_store. Its comments_on reads an issue's comments. Its assign, close, person_files, score and block change the tracker as a person or the plan store would. Its account is the display name of the account the store works as."""
import re
import typing
@@ -23,6 +23,9 @@ class EpicStoreContract:
"""Assigns the issue named key to the person whose display name is name."""
raise NotImplementedError
def account(self, store: EpicStore) -> str:
raise NotImplementedError
def close(self, store: EpicStore, key: str, status: str) -> None:
"""Moves the issue named key to the done status named status."""
raise NotImplementedError
@@ -151,6 +154,23 @@ class EpicStoreContract:
self.assertIsInstance(store.add_label("ZZZ-1", "repo:log"), Failure)
self.assertEqual([issue.labels for issue in self.issues(store)], [(), ()])
def test_starts_an_issue_nobody_holds_as_its_own_account_and_answers_who_else_holds_one(self) -> None:
store = self.new_store()
free = self.filed(store, store.epic_key, "Count the runs.")
held = self.filed(store, store.epic_key, "Ship the later thing.")
task = self.filed(store, free, "Count them in the api.")
untouched = self.filed(store, store.epic_key, "Close the old thing.")
self.assign(store, held, "Ada Berg")
self.assertEqual([store.start_issue(free), store.start_issue(held), store.start_issue(task), store.start_issue(free)], [None, "Ada Berg", None, None])
self.assertEqual({issue.key: issue.assignee for issue in self.issues(store)}, {free: self.account(store), held: "Ada Berg", task: self.account(store), untouched: None})
def test_refuses_to_start_an_issue_outside_the_epic(self) -> None:
store = self.new_store()
self.filed(store, store.epic_key, "Count the runs.")
self.assertIsInstance(store.start_issue("ZZZ-1"), Failure)
self.assertIsInstance(store.start_issue("not a key"), Failure)
self.assertEqual([issue.assignee for issue in self.issues(store)], [None])
def test_finishes_a_child_issue_so_it_reads_as_done_and_leaves_one_that_is_done_as_it_is(self) -> None:
store = self.new_store()
key = self.filed(store, store.epic_key, "Count the runs.")
+14 -1
View File
@@ -7,13 +7,15 @@ from failure import Failure
@dataclasses.dataclass
class MemoryEpic:
"""An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment, rank, scoring, issue finish and closing fails with it as the reason. comments holds each issue's comments, and the epic's, by key. done says whether the epic is closed. writes says each write that succeeded, in order."""
"""An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment, rank, scoring, issue start, issue finish and closing fails with it as the reason. comments holds each issue's comments, and the epic's, by key. done says whether the epic is closed. writes says each write that succeeded, in order."""
epic_key: str
issues: list[EpicIssue] = dataclasses.field(default_factory=list)
comments: dict[str, list[str]] = dataclasses.field(default_factory=dict)
fails: str | None = None
done: bool = False
writes: list[str] = dataclasses.field(default_factory=list)
# The display name of the account the epic's issues are started as.
account: str = "do-epic"
def read(self) -> list[EpicIssue] | Failure:
if self.fails:
@@ -102,6 +104,17 @@ class MemoryEpic:
self.writes.append(f"score {key} {', '.join(f'{name} {value}' for name, value in scores.items())}, Moves {moves or 'none'}, with the comment: {comment.strip()}")
return None
def start_issue(self, key: str) -> str | None | Failure:
if self.fails:
return Failure(self.fails)
child = self.within(key)
if child is None:
return no_child(self.epic_key, key, "started")
self.writes.append(f"start {key}")
if child.assignee is None:
self.change(key, assignee=self.account)
return None if child.assignee in (None, self.account) else child.assignee
def finish_issue(self, key: str) -> None | Failure:
if self.fails:
return Failure(self.fails)
+30 -11
View File
@@ -12,6 +12,7 @@ from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent,
from failure import Failure
from plan.todo_table import MOVES
from do_epic.repo_pick import REVIEW_LABEL
from do_epic.backend.jira_start import Start, started
FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"]
# How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes.
@@ -40,6 +41,7 @@ class JiraEpic:
# The issue types that a finding, and a release review (an issue labelled REVIEW_LABEL), are filed as.
finding_type: str = DEFAULT_ISSUE_TYPE
review_type: str = DEFAULT_ISSUE_TYPE
start: Start = Start()
@property
def epic_key(self) -> str:
@@ -195,21 +197,24 @@ class JiraEpic:
put = self.http("PUT", f"{self.epic.site}/rest/api/3/issue/{key}", authorization, {"properties": [{"key": PROPERTY, "value": held | scores | {MOVES: moves}}]})
return Failure(f"the comment on {key} tells its team the scores, but they could not be set, so the next run scores it again: {put.reason}") if isinstance(put, Failure) else None
def start_issue(self, key: str) -> str | None | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
within = self.within(key, authorization, "start", "started")
if isinstance(within, Failure):
return within
# Jira keeps a sub-task in its parent's sprint, so the parent joins the sprint in its place.
return started(self.epic.site, key, key if within[0] == self.epic_key else within[0], self.start, authorization, self.http)
def finish_issue(self, key: str) -> None | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
placed = self.placed(key, authorization, "to finish it")
if isinstance(placed, Failure):
return placed
above, done = placed
# A sub-task is no child of the epic but its parent is, so a sub-task's parent is read too.
grand = self.parent_of(above, authorization, "to finish its sub-task") if above not in (None, self.epic_key) else None
if isinstance(grand, Failure):
return grand
if above is None or (above != self.epic_key and grand != self.epic_key):
return no_child(self.epic_key, key, "finished")
if done:
within = self.within(key, authorization, "finish", "finished")
if isinstance(within, Failure):
return within
if within[1]:
return None
if self.finish is None:
return Failure(NO_FINISH.format(to="finish an issue", transition=JIRA_FINISH_TRANSITION, status=JIRA_FINISH_STATUS))
@@ -219,6 +224,20 @@ class JiraEpic:
refused = move_refusal(self.epic.site, key, transition, self.finish, authorization, self.http)
return Failure(f"{refused}; {PERHAPS_MOVED.format(key=key)}") if refused else None
def within(self, key: str, authorization: str, do: str, done_to_it: str) -> tuple[str, bool] | Failure:
"""The key of the parent of key, which is a child issue of the epic or a sub-task of one, and whether key's status is a done one; any other key is refused. do and done_to_it say what was asked of key, such as "finish" and "finished"."""
placed = self.placed(key, authorization, f"to {do} it")
if isinstance(placed, Failure):
return placed
above, done = placed
# A sub-task is no child of the epic but its parent is, so a sub-task's parent is read too.
grand = self.parent_of(above, authorization, f"to {do} its sub-task") if above not in (None, self.epic_key) else None
if isinstance(grand, Failure):
return grand
if above is None or (above != self.epic_key and grand != self.epic_key):
return no_child(self.epic_key, key, done_to_it)
return above, done
def not_a_parent(self, parent: str, authorization: str) -> Failure | None:
"""Why nothing can be filed under parent; None where it is the epic or one of its child issues."""
if parent == self.epic_key:
+96
View File
@@ -0,0 +1,96 @@
"""How a Jira issue shows its team that its work is under way: assigned, moved by the team's start transition and in a board's active sprint. JiraEpic.start_issue calls `started` for an issue it found in its epic."""
import dataclasses
import typing
from atlassian.client import Http
from atlassian.jira import offers_of, unshaped
from failure import Failure
# Three readers, seated as those who write and read do-epic's config, picked both spellings from four candidates each, 3-0. `jira-start-transition` pairs with `jira-finish-transition`. `jira-board` reads as the board do-epic takes its issues from.
START_TRANSITION = "jira-start-transition"
SPRINT_BOARD = "jira-sprint-board"
# The key of the category Jira gives each status at which an issue's work hasn't started.
NEW = "new"
@dataclasses.dataclass(frozen=True)
class Start:
"""What the machine's settings give a starting issue beside its assignee: transition names the workflow transition that moves it, and sprint_board is the ID of the board whose active sprint it joins. Each is None where the settings don't name it."""
transition: str | None = None
sprint_board: int | None = None
@dataclasses.dataclass(frozen=True)
class Held:
"""An issue as Jira holds it before it starts. holder is its assignee's account ID and display name; None where nobody is assigned."""
holder: tuple[str, str] | None
status: str
category: str
def started(site: str, key: str, sprint_key: str, start: Start, authorization: str, http: Http) -> str | None | Failure:
"""Starts the issue named key, where sprint_key is the issue a sprint takes for it: the issue itself, or the parent of a sub-task. The answer is the display name of someone else who holds the issue, else None; a Failure names the first step Jira did not take."""
held = held_of(site, key, authorization, http)
if isinstance(held, Failure):
return held
other = assigned(site, key, held, authorization, http)
# A status in any later category, such as Code Review, is past the start transition, so the issue keeps it.
moved = move_refusal(site, key, held.status, start.transition, authorization, http) if start.transition and held.category == NEW else None
joined = sprint_refusal(site, sprint_key, start.sprint_board, authorization, http) if start.sprint_board is not None else None
return next((step for step in (other, moved, joined) if isinstance(step, Failure)), other)
def held_of(site: str, key: str, authorization: str, http: Http) -> Held | Failure:
answered: typing.Any = http("GET", f"{site}/rest/api/3/issue/{key}?fields=assignee,status", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read {key} to start it: {answered.reason}")
try:
assignee, status = answered["fields"]["assignee"], answered["fields"]["status"]
return Held(None if assignee is None else (str(assignee["accountId"]), str(assignee["displayName"])), str(status["name"]), str(status["statusCategory"]["key"]))
except (KeyError, TypeError) as failure:
return Failure(unshaped(key, failure))
def assigned(site: str, key: str, held: Held, authorization: str, http: Http) -> str | None | Failure:
"""Assigns the issue named key to the account authorization names, unless someone holds it. The display name of someone else who holds it, else None."""
me = http("GET", f"{site}/rest/api/3/myself", authorization, None)
if isinstance(me, Failure):
return Failure(f"cannot read which account do-epic works as, to assign {key}: {me.reason}")
account = me.get("accountId") if isinstance(me, dict) else None
if not isinstance(account, str):
return Failure(f"cannot assign {key}: Jira named no account ID for the account do-epic works as")
if held.holder is not None:
return None if held.holder[0] == account else held.holder[1]
put = http("PUT", f"{site}/rest/api/3/issue/{key}/assignee", authorization, {"accountId": account})
return Failure(f"cannot assign {key}: {put.reason}") if isinstance(put, Failure) else None
def move_refusal(site: str, key: str, status: str, transition: str, authorization: str, http: Http) -> Failure | None:
"""Moves the issue named key, which has the status named status, by the transition named transition. Why Jira did not take the move; None where it did."""
offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None)
if isinstance(offered, Failure):
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
offers = offers_of(offered, key)
if isinstance(offers, Failure):
return offers
named = [id_ for id_, name, _, _ in offers if name == transition]
if not named:
others = " and ".join(f"{name!r} to {to!r}" for _, name, to, _ in offers)
return Failure(f"{key} has no transition {transition!r} from its status {status!r}, " + (f"only {others}: name in `{START_TRANSITION}` one that its statuses before work starts have" if offers else "nor any other the account may make"))
moved = http("POST", f"{site}/rest/api/3/issue/{key}/transitions", authorization, {"transition": {"id": named[0]}})
return Failure(f"cannot move {key} by {transition!r}: {moved.reason}") if isinstance(moved, Failure) else None
def sprint_refusal(site: str, key: str, board: int, authorization: str, http: Http) -> Failure | None:
"""Adds the issue named key to the one active sprint of the board with the ID board. Why it joined none; None where it joined."""
answered = http("GET", f"{site}/rest/agile/1.0/board/{board}/sprint?state=active", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read the active sprint of board {board}, which `{SPRINT_BOARD}` names: {answered.reason}")
values = answered.get("values") if isinstance(answered, dict) else None
sprints = [each["id"] for each in values if isinstance(each, dict) and isinstance(each.get("id"), int)] if isinstance(values, list) else []
if not isinstance(values, list) or len(sprints) != len(values):
return Failure(f"Jira answered board {board}'s sprints in a shape other than the one it documents")
if len(sprints) != 1:
return Failure(f"board {board}, which `{SPRINT_BOARD}` names, has {len(sprints) or 'no'} active sprint{'s' * (len(sprints) > 1)}, so {key} joins none")
added = http("POST", f"{site}/rest/agile/1.0/sprint/{sprints[0]}/issue", authorization, {"issues": [key]})
return Failure(f"cannot add {key} to the active sprint of board {board}: {added.reason}") if isinstance(added, Failure) else None
+3
View File
@@ -67,6 +67,9 @@ class EpicStore(typing.Protocol):
def set_scores(self, key: str, scores: dict[str, int], moves: str, comment: str) -> None | Failure:
"""Posts comment, markdown, on the epic's child issue named key, or on a sub-task of one, then sets its scores. The comment tells the team the scores, since a tracker's screens may not show them. scores holds each of L, E, I and S, and moves is the plan's Moves cell, which may be empty. An issue that holds a score keeps what it holds and is refused, as are an issue outside the epic and a blank comment. Where the scores cannot be set after the comment is posted, the Failure says so."""
def start_issue(self, key: str) -> str | None | Failure:
"""Shows the team that the epic's child issue named key, or a sub-task of one, is being worked. It assigns an issue nobody holds to the account the store works as. An issue someone else holds stays theirs, and the answer is their display name; otherwise the answer is None. Where the backend's settings say so, it also moves an issue whose work hasn't started and adds it to a sprint. An issue outside the epic is refused. A Failure names the first step that could not be made; each other step stands where the tracker took it."""
def finish_issue(self, key: str) -> None | Failure:
"""Moves the epic's child issue named key, or a sub-task of one, to a done status, so that read answers it as done; one already done stays as it is. An issue outside the epic is refused. A Failure says why the move could not be made: the issue's workflow gives no way to a done status, gives several the backend cannot choose between, or refuses the move."""
+3
View File
@@ -18,6 +18,9 @@ class MemoryEpicContract(EpicStoreContract, unittest.TestCase):
def assign(self, store: MemoryEpic, key: str, name: str) -> None: # type: ignore[override]
store.change(key, assignee=name)
def account(self, store: MemoryEpic) -> str: # type: ignore[override]
return store.account
def comments_on(self, store: MemoryEpic, key: str) -> list[str]: # type: ignore[override]
return store.comments.get(key, [])
+99 -1
View File
@@ -14,6 +14,7 @@ from failure import Failure
from do_epic.backend.jira import JiraEpic
from adf_codec.convert import Refused
from do_epic.repo_pick import REVIEW_LABEL
from do_epic.backend.jira_start import Start
SITE = "https://acme.atlassian.net"
EPIC = Epic(SITE, "ABC-12")
@@ -25,6 +26,11 @@ ISSUES = f"{SITE}/rest/api/3/issue"
RANK = f"{SITE}/rest/agile/1.0/issue/rank"
TO_DO = {"name": "To Do", "statusCategory": {"key": "new"}}
DONE = {"name": "Done", "statusCategory": {"key": "done"}}
IN_PROGRESS = {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}
MYSELF = f"{SITE}/rest/api/3/myself"
ME = {"accountId": "712020:do-epic", "displayName": "Do Epic"}
ACTIVE_SPRINTS = f"{SITE}/rest/agile/1.0/board/6/sprint?state=active"
SPRINT_ISSUES = f"{SITE}/rest/agile/1.0/sprint/77/issue"
TRANSITIONS = f"{ISSUES}/ABC-12/transitions"
EPIC_COMMENT = f"{ISSUES}/ABC-12/comment"
EPIC_STATUS = f"{ISSUES}/ABC-12?fields=status"
@@ -55,6 +61,9 @@ class FakeJira:
workflow: list[dict[str, object]] = dataclasses.field(default_factory=lambda: [{"id": "31", "name": "Mark as done", "to": DONE}])
# The epic's own status, which the transition "Mark as done" moves to DONE.
epic_status: dict[str, object] = dataclasses.field(default_factory=lambda: dict(TO_DO))
# The active sprints of board 6, and the issues each request added to sprint 77.
sprints: list[object] = dataclasses.field(default_factory=lambda: [{"id": 77, "name": "Sprint 9", "state": "active"}])
sprinted: list[object] = dataclasses.field(default_factory=list)
def __call__(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url))
@@ -87,9 +96,21 @@ class FakeJira:
return {"transitions": [] if held["fields"]["status"] == DONE else self.workflow} # type: ignore[index]
if method == "POST" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/transitions"), None)):
assert isinstance(body, dict)
held["fields"]["status"] = DONE # type: ignore[index]
held["fields"]["status"] = next(offer["to"] for offer in self.workflow if offer["id"] == body["transition"]["id"]) # type: ignore[index]
self.transitioned.append(body["transition"]["id"])
return None
if method == "GET" and url == MYSELF:
return ME
if method == "PUT" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/assignee"), None)):
assert body == {"accountId": ME["accountId"]}, body
held["fields"]["assignee"] = ME # type: ignore[index]
return None
if method == "GET" and url == ACTIVE_SPRINTS:
return {"values": self.sprints}
if method == "POST" and url == SPRINT_ISSUES:
assert isinstance(body, dict)
self.sprinted.append(body["issues"])
return None
if method == "POST" and url == ISSUES:
return self.created(body)
if method == "PUT" and url == RANK:
@@ -172,6 +193,9 @@ class JiraEpicContract(Case, EpicStoreContract):
def assign(self, store: JiraEpic, key: str, name: str) -> None: # type: ignore[override]
self.jira.change(key, assignee={"accountId": "5b10a2844c20165700ede21g", "displayName": name})
def account(self, store: JiraEpic) -> str: # type: ignore[override]
return ME["displayName"]
def comments_on(self, store: JiraEpic, key: str) -> list[str]: # type: ignore[override]
return [to_markdown([document])[0].strip() for document in self.jira.comments.get(key, [])] # type: ignore[misc]
@@ -271,6 +295,80 @@ class Jira(Case):
self.jira.answers[("GET", EPIC_STATUS)] = answer
self.assertEqual(self.new_store().closed(), Failure(reason))
def starting(self, start: Start = Start("Start", 6)) -> JiraEpic:
"""A store whose settings name start, on a workflow that has the transition Start to In Progress."""
self.jira.workflow.append({"id": "21", "name": "Start", "to": IN_PROGRESS})
return dataclasses.replace(self.new_store(), start=start)
def test_starts_an_issue_by_the_transition_and_into_the_active_sprint_of_the_board_the_settings_name(self) -> None:
store = self.starting()
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str)
self.assertIsNone(store.start_issue(key))
self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ME, IN_PROGRESS)) # type: ignore[index]
self.assertEqual((self.jira.transitioned, self.jira.sprinted), (["21"], [[key]]))
def test_a_starting_sub_tasks_parent_joins_the_sprint_in_its_place(self) -> None:
store = self.starting()
child = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(child, str)
task = store.file(child, "Count them in the api.", "", ())
assert isinstance(task, str)
self.assertIsNone(store.start_issue(task))
self.assertEqual(self.jira.sprinted, [[child]])
self.assertEqual([issue["fields"]["status"] for issue in self.jira.issues], [TO_DO, IN_PROGRESS]) # type: ignore[index]
def test_an_issue_past_the_start_keeps_its_status_and_one_someone_holds_keeps_its_holder(self) -> None:
store = self.starting()
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str)
review = {"name": "Code Review", "statusCategory": {"key": "indeterminate"}}
ada = {"accountId": "5b10a2844c20165700ede21g", "displayName": "Ada Berg"}
self.jira.change(key, status=review, assignee=ada)
self.assertEqual(store.start_issue(key), "Ada Berg")
self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ada, review)) # type: ignore[index]
self.assertEqual((self.jira.transitioned, self.jira.sprinted), ([], [[key]]))
self.assertNotIn(("GET", f"{ISSUES}/{key}/transitions"), self.jira.calls)
def test_without_the_settings_a_start_only_assigns(self) -> None:
store = self.starting(Start())
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str)
self.assertIsNone(store.start_issue(key))
self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ME, TO_DO)) # type: ignore[index]
self.assertEqual(self.jira.calls[-2:], [("GET", MYSELF), ("PUT", f"{ISSUES}/{key}/assignee")])
def test_a_start_names_the_first_step_jira_did_not_take_and_makes_the_others(self) -> None:
store = self.starting()
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str)
transitions, assignee = f"{ISSUES}/{key}/transitions", f"{ISSUES}/{key}/assignee"
for answers, reason in (
({("GET", f"{ISSUES}/{key}?fields=assignee,status"): Failure("Jira answered 503")}, f"cannot read {key} to start it: Jira answered 503"),
({("GET", f"{ISSUES}/{key}?fields=assignee,status"): {"fields": {"assignee": None}}}, f"{key} is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"),
({("GET", MYSELF): Failure("Jira answered 503")}, f"cannot read which account do-epic works as, to assign {key}: Jira answered 503"),
({("GET", MYSELF): {"displayName": "Do Epic"}}, f"cannot assign {key}: Jira named no account ID for the account do-epic works as"),
({("PUT", assignee): Failure("Jira answered 403")}, f"cannot assign {key}: Jira answered 403"),
({("GET", transitions): Failure("Jira answered 503")}, f"cannot read {key}'s transitions: Jira answered 503"),
({("GET", transitions): {"transitions": [{"id": "21"}]}}, f"Jira answered {key}'s transitions in a shape other than the one it documents"),
({("GET", transitions): {"transitions": [{"id": "31", "name": "Mark as done", "to": DONE}]}}, f"{key} has no transition 'Start' from its status 'To Do', only 'Mark as done' to 'Done': name in `jira-start-transition` one that its statuses before work starts have"),
({("GET", transitions): {"transitions": []}}, f"{key} has no transition 'Start' from its status 'To Do', nor any other the account may make"),
({("POST", transitions): Failure("Jira answered 400")}, f"cannot move {key} by 'Start': Jira answered 400"),
({("GET", ACTIVE_SPRINTS): Failure("Jira answered 400")}, f"cannot read the active sprint of board 6, which `jira-sprint-board` names: Jira answered 400"),
({("GET", ACTIVE_SPRINTS): {"values": [{"name": "Sprint 9"}]}}, "Jira answered board 6's sprints in a shape other than the one it documents"),
({("GET", ACTIVE_SPRINTS): {"values": []}}, f"board 6, which `jira-sprint-board` names, has no active sprint, so {key} joins none"),
({("GET", ACTIVE_SPRINTS): {"values": [{"id": 77}, {"id": 78}]}}, f"board 6, which `jira-sprint-board` names, has 2 active sprints, so {key} joins none"),
({("POST", SPRINT_ISSUES): Failure("Jira answered 403")}, f"cannot add {key} to the active sprint of board 6: Jira answered 403"),
):
with self.subTest(reason=reason):
self.jira.change(key, status=TO_DO, assignee=None)
self.jira.answers, self.jira.sprinted = answers, []
self.assertEqual(store.start_issue(key), Failure(reason))
self.jira.answers = {("PUT", assignee): Failure("Jira answered 403")}
self.jira.change(key, status=TO_DO, assignee=None)
store.start_issue(key)
self.assertEqual((self.jira.issues[0]["fields"]["status"], self.jira.sprinted), (IN_PROGRESS, [[key]])) # type: ignore[index]
def test_finishes_an_issue_by_the_transition_the_settings_name(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
+20 -2
View File
@@ -17,6 +17,8 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d
- `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out.
- `language` is the default language of Jira text, by its English name. English where left out.
- `jira-finish-transition` and `jira-finish-status` name the workflow transition that moves a finished chunk's issue and closes a finished epic, such as "Mark as done", and the status it leads to, such as "Done". A project's config names a plan item's the same way. Set both or neither; without them do-epic moves no issue to done and closes no epic.
- `jira-start-transition` names the workflow transition that moves an issue as its chunk starts, such as "In Progress". An issue whose work has started already, such as one in Code Review, keeps its status. Without it do-epic doesn't move a starting issue.
- `jira-sprint-board` is the ID of a Jira board, the number in the board's address, such as `6`. An issue whose chunk starts joins that board's active sprint; a sub-task's parent joins in its place. Without it do-epic adds no issue to a sprint.
- `jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks. A status Jira counts as done always does both, listed or not.
- `jira-automation-moves-issues = true` says the team's own automation moves an issue when its pull request merges. do-epic then moves only the issue of a chunk without a repo, which has no pull request, and waits for the automation to move each other. It needs `jira-unblocking-statuses`, which then names the status the automation gives an issue whose pull request merged. false where left out.
- `jira-finding-type` names the Jira issue type do-epic files a finding as, and `jira-review-type` the one it files a repo's release review as, such as `"Feature"` and `"Chore"`, for a Jira project that has no Task type. Task where left out. do-epic doesn't file anything where the project lacks the type, and says which types it has.
@@ -36,6 +38,7 @@ from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME, REVIEW_LABEL
from text_files.markdown_text import listed
from model_routing.ladder_file import read_ladder, SHIPPED
from do_epic.split import SPLIT_LABEL
from do_epic.backend.jira_start import SPRINT_BOARD, Start, START_TRANSITION
REPO_RULE = "repo-rule.md"
# Three readers, seated as the human who writes this config, picked these spellings from four candidates each, 3-0: `jira-url` over `site`, `clone-folder` over `repos-folder` (which reads as the folder of repos that already exist) and `repoless-model` over `no-repo-model`. `env-file` and `language` keep the names a project's config gives them.
@@ -50,7 +53,7 @@ UNBLOCKING_STATUSES = "jira-unblocking-statuses"
AUTOMATION_MOVES = "jira-automation-moves-issues"
SUB_TASK_SUMMARY = "sub-task-summary"
ISSUE_TYPES = (JIRA_FINDING_TYPE, JIRA_REVIEW_TYPE)
OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH, UNBLOCKING_STATUSES, AUTOMATION_MOVES, LABEL_REPOS, SUB_TASK_SUMMARY, *ISSUE_TYPES)
OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH, START_TRANSITION, SPRINT_BOARD, UNBLOCKING_STATUSES, AUTOMATION_MOVES, LABEL_REPOS, SUB_TASK_SUMMARY, *ISSUE_TYPES)
LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTIONAL, 'and')}."
@@ -75,6 +78,8 @@ class DoEpicConfig:
sub_task_summary: str | None = None
finding_type: str = DEFAULT_ISSUE_TYPE
review_type: str = DEFAULT_ISSUE_TYPE
# What a starting chunk's issue gets beside its assignee.
start: Start = Start()
def label_repo_faults(table: object) -> list[str]:
@@ -106,6 +111,16 @@ def summary_template_faults(template: object) -> list[str]:
]
def start_faults(values: dict[str, object]) -> list[str]:
"""What is wrong with the START_TRANSITION and SPRINT_BOARD settings in values."""
transition, board = values.get(START_TRANSITION), values.get(SPRINT_BOARD)
return [
*([f"`{START_TRANSITION}` is {transition!r}, not the name Jira shows, such as \"In Progress\""] if START_TRANSITION in values and not name_of(transition) else []),
# TOML reads true as a bool, which Python counts as the whole number 1.
*([f"`{SPRINT_BOARD}` is {board!r}, not a board's ID, the whole number in the board's address, such as 6"] if SPRINT_BOARD in values and not (isinstance(board, int) and not isinstance(board, bool) and board > 0) else []),
]
def workflow_faults(values: dict[str, object]) -> list[str]:
"""What is wrong with the UNBLOCKING_STATUSES list and the AUTOMATION_MOVES switch in values."""
statuses, moves = values.get(UNBLOCKING_STATUSES, ["Done"]), values.get(AUTOMATION_MOVES, False)
@@ -148,6 +163,7 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi
*([f"`{REPOLESS_MODEL}` is {model!r}, not a model on the routing ladder: {', '.join(models)}"] if REPOLESS_MODEL in values and model not in models else []),
*finish_faults(values),
*workflow_faults(values),
*start_faults(values),
*(summary_template_faults(values[SUB_TASK_SUMMARY]) if SUB_TASK_SUMMARY in values else []),
*label_repo_faults(values.get(LABEL_REPOS, {})),
*(f"`{name}` is {values[name]!r}, {fault}" for name, example in zip(ISSUE_TYPES, ("Feature", "Chore")) if name in values and (fault := type_fault(values[name], example))),
@@ -164,4 +180,6 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi
template = values.get(SUB_TASK_SUMMARY)
assert template is None or isinstance(template, str)
finding_type, review_type = (str(values.get(name, DEFAULT_ISSUE_TYPE)) for name in ISSUE_TYPES)
return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values), types.MappingProxyType(labels), tuple(statuses), values.get(AUTOMATION_MOVES) is True, template, finding_type, review_type)
board = values.get(SPRINT_BOARD)
assert board is None or isinstance(board, int)
return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values), types.MappingProxyType(labels), tuple(statuses), values.get(AUTOMATION_MOVES) is True, template, finding_type, review_type, Start(name_of(values.get(START_TRANSITION)), board))
+12 -1
View File
@@ -83,7 +83,7 @@ Backend = typing.Callable[[DoEpicConfig, str], tuple[EpicStore, EpicRecord]]
def jira_backend(config: DoEpicConfig, key: str) -> tuple[EpicStore, EpicRecord]:
epic = Epic(config.jira_url, key)
return JiraEpic(epic, config.env_file, finish=config.finish, finding_type=config.finding_type, review_type=config.review_type), EpicRecord(EpicDescription(epic, config.env_file))
return JiraEpic(epic, config.env_file, finish=config.finish, finding_type=config.finding_type, review_type=config.review_type, start=config.start), EpicRecord(EpicDescription(epic, config.env_file))
@dataclasses.dataclass(frozen=True)
@@ -305,6 +305,8 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
if isinstance(place, Stop):
return place
root, repo = place
if issue:
issue_started(key, epic)
if unmade := folder_made(root):
return Stop(1, unmade.reason)
session = session_named(f"A {epic.key} do-epic {key}", epic.paths.claude_code_transcripts)
@@ -335,6 +337,15 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
return handed_on(key, epic, repo is not None)
def issue_started(key: str, epic: EpicRun) -> None:
"""Starts the issue called key in the tracker, and says who else holds it, or why it didn't start. The chunk runs either way: the tracker shows the team the work, and the work doesn't read it."""
other = epic.store.start_issue(key)
if isinstance(other, Failure):
say(f"{key} doesn't show in the tracker as started, and its chunk runs all the same: {other.reason}", epic.effects, stdout=True)
elif other:
say(f"{key} stays assigned to {other}, who holds it", epic.effects, stdout=True)
def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool) -> str | Stop:
"""Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh.
+15
View File
@@ -8,6 +8,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.config import DoEpicConfig, load
from failure import Failure
from project_config.settings import Finish
from do_epic.backend.jira_start import Start
SETTINGS = """jira-url = "https://acme.atlassian.net"
env-file = "~/jira.env"
@@ -113,6 +114,20 @@ class ConfigTest(unittest.TestCase):
self.write(SETTINGS + 'jira-finish-status = " "\n')
self.assertIn('`jira-finish-status` is \' \', not the name Jira shows, such as "Done"; `jira-finish-status` is set, so `jira-finish-transition` must be too', self.failure())
def test_reads_how_a_starting_issue_moves_and_which_boards_sprint_it_joins(self) -> None:
self.write(SETTINGS)
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.start, Start(None, None))
self.write(SETTINGS + 'jira-start-transition = "In Progress"\njira-sprint-board = 6\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.start, Start("In Progress", 6))
for board, read in (('"6"', "'6'"), ("0", "0"), ("true", "True"), ("6.0", "6.0")):
with self.subTest(board=board):
self.write(SETTINGS + f'jira-start-transition = " "\njira-sprint-board = {board}\n')
self.assertIn(f"`jira-start-transition` is ' ', not the name Jira shows, such as \"In Progress\"; `jira-sprint-board` is {read}, not a board's ID, the whole number in the board's address, such as 6", self.failure())
def test_reads_the_unblocking_statuses_and_that_the_teams_automation_moves_issues(self) -> None:
self.write(SETTINGS)
found = load(self.home)
+32
View File
@@ -30,6 +30,7 @@ from text_files.file_writes import replace_file
from model_routing.route import Route
from model_routing.ladder import Rung
from do_epic.test_do_epic import SETTINGS
from do_epic.backend.jira_start import Start
DESCRIPTION = "**Max parallel chunks:** 2\n\n## Goals\nShip the import.\n\n## Audience\nThe client's team.\n"
@@ -104,6 +105,11 @@ class TheJiraBackend(unittest.TestCase):
self.assertEqual((store.epic, store.env_file, store.finish), (Epic("https://acme.atlassian.net", "ABC-12"), pathlib.Path("/h/jira.env"), Finish("Mark as done", "Done"))) # type: ignore[attr-defined]
self.assertEqual((record.description.epic, record.description.env_file), (store.epic, store.env_file)) # type: ignore[attr-defined]
def test_starts_an_issue_as_the_config_says(self) -> None:
config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", start=Start("In Progress", 6))
store, _ = main.jira_backend(config, "ABC-12")
self.assertEqual(store.start, Start("In Progress", 6)) # type: ignore[attr-defined]
def test_files_the_issue_types_the_config_names(self) -> None:
config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", finding_type="Feature", review_type="Chore")
store, _ = main.jira_backend(config, "ABC-12")
@@ -368,6 +374,32 @@ class AChunksRun(DoEpicTest):
# The one claude call is the judge's: ABC-22, which no label places, waits for the human's do-epic.
self.assertEqual(len(fake.made("claude")), 1)
def started(self, store: MemoryEpic) -> str:
"""What the chunk of ABC-21 prints as it runs to its end on store."""
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[assignment, method-assign, arg-type]
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n"), MODELS)
self.assertEqual(code, 0, err)
return out
def test_a_starting_chunk_starts_its_issue_in_the_tracker_before_its_first_cycle(self) -> None:
store = MemoryEpic("ABC-12", list(self.issues))
out = self.started(store)
self.assertEqual((store.writes[0], store.issues[1].assignee), ("start ABC-21", "do-epic"))
self.assertNotIn("assigned", out.partition("=== cycle 1")[0])
def test_a_starting_chunk_says_who_else_holds_its_issue_and_leaves_it_theirs(self) -> None:
store = MemoryEpic("ABC-12", [self.issues[0], dataclasses.replace(self.issues[1], assignee="Ada Berg")])
self.assertIn("ABC-21 stays assigned to Ada Berg, who holds it\n", self.started(store).partition("=== cycle 1")[0])
self.assertEqual(store.issues[1].assignee, "Ada Berg")
def test_a_chunk_runs_though_its_issue_could_not_start_in_the_tracker_and_says_why(self) -> None:
class Unstartable(MemoryEpic):
def start_issue(self, key: str) -> str | None | Failure:
return Failure(f"cannot assign {key}: Jira answered 403")
out = self.started(Unstartable("ABC-12", list(self.issues)))
self.assertIn("ABC-21 doesn't show in the tracker as started, and its chunk runs all the same: cannot assign ABC-21: Jira answered 403\n", out.partition("=== cycle 1")[0])
self.assertIn("the chunk finished", out)
def test_runs_cycles_until_the_judge_rules_it_finished_then_starts_the_next_chunk(self) -> None:
self.issues.append(issue("ABC-22", "do-epic-claude"))
self.description = DESCRIPTION.replace("2", "1")