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
+1 -1
View File
@@ -120,7 +120,7 @@ A client that plans in Jira Cloud names an epic as its project's plan: `plan = "
- A blocker is an "is blocked by" link to another open child.
- The scores are the issue property `plan-item`, a JSON object such as `{"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}`. An issue without it reads as an item nobody scored yet.
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it. The loop reads such a plan and files items into it, each as a Task under the epic. `todo-item edit` and `move` change only an issue the loop filed. Of an issue a person filed, `edit` sets only the scores, and posts its `--comment` on the issue to tell the team why; the summary, description and Fix Version stay the team's to change in Jira, as do every issue's links. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it. The loop reads such a plan and files items into it, each as a Task under the epic. The config also states the formula and the bar that todo.md's `## Scoring` would, such as `jira-score-formula = "100 * V / (2**S + 8)"` and `jira-score-bar = 1`, and fails to load without them. `todo-item add` refuses an item that scores under the bar, unless it is exempt. It ranks the new issue among the issues the loop filed, by score, with security findings first. A person's issues keep the rank the team gave them. `todo-item edit` and `move` change only an issue the loop filed. Of an issue a person filed, `edit` sets only the scores, and posts its `--comment` on the issue to tell the team why; the summary, description and Fix Version stay the team's to change in Jira, as do every issue's links. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
A client that keeps its goals and audience in an epic's description names that epic as the goals file: `goals-and-audience = "jira:https://acme.atlassian.net/browse/ABC-12"`, which may be the plan's own epic. Such a config keeps its plan in Jira too, and reads both with the same `env-file`. The description needs `## Goals` and `## Audience` as headings, level-2 headings in Jira's editor. The loop only reads the description, so edit it in Jira; `project-record open goals-and-audience` prints a file holding its text. Whoever may edit that description sets the premises every worker and judge follows, so keep its edit rights to the people who own the project's goals.
+2 -2
View File
@@ -983,7 +983,7 @@ class LarvReviewTool(unittest.TestCase):
checkout = pathlib.Path(temp, "acme")
checkout.mkdir()
config = configured(self, checkout) / "config.toml"
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
(checkout / "todo.md").write_text("the owners' own notes\n")
self.enterContext(contextlib.chdir(checkout))
said: list[str] = []
@@ -1250,7 +1250,7 @@ class LarvReviewTool(unittest.TestCase):
credentials = self.config.parents[2] / "acme.env"
credentials.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
credentials.chmod(0o600)
self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\n')
self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
ran = self.run_tool("reviewer-header", "prose")
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("cannot read the epic ABC-12", ran.stderr)
+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)
+33 -12
View File
@@ -13,7 +13,7 @@ from failure import Failure
from git_cli.git_repo import file_at, git, Git
from record_store.stores import goals_store, store as record_store, RecordStore
from plan_store import markdown_edits
from project_config.settings import ProjectConfig
from project_config.settings import ProjectConfig, Scoring
from release_plan import ranking
from release_plan.release import Release
from text_files.file_writes import replace_file
@@ -139,16 +139,36 @@ class FilePlan:
plan = read_text(self.path, MISSING)
if isinstance(plan, Failure):
return plan
goals = self.goals.read()
if isinstance(goals, Failure):
return goals
if not goals:
return Failure(f"{self.goals.label}: missing or empty; {GOALS_HINT}")
decisions = self.decisions.read()
if isinstance(decisions, Failure):
return decisions
history = self.history.read()
return history if isinstance(history, Failure) else (plan, goals, decisions, history)
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
@dataclasses.dataclass(frozen=True)
class StatedScoring:
"""The scoring that the project's config states for a plan in Jira, whose goal weights ranking reads from the goals file, the decision log and the comprehension history."""
stated: Scoring
goals: RecordStore
decisions: RecordStore
history: RecordStore
floor: decimal.Decimal
def read(self) -> ranking.Scoring | Failure:
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor)
def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure:
"""What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure."""
goals_text = goals.read()
if isinstance(goals_text, Failure):
return goals_text
if not goals_text:
return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}")
decisions_text = decisions.read()
if isinstance(decisions_text, Failure):
return decisions_text
history_text = history.read()
return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text)
def store(config: ProjectConfig) -> PlanStore:
@@ -159,7 +179,8 @@ def store(config: ProjectConfig) -> PlanStore:
from plan_store.jira_epic import JiraPlan
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
return JiraPlan(config.epic, config.env_file, finish_by=config.jira_finish)
scoring = StatedScoring(config.jira_scoring, goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), config.readability_floor) if config.jira_scoring else None
return JiraPlan(config.epic, config.env_file, finish_by=config.jira_finish, scoring=scoring)
def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan:
+84 -4
View File
@@ -1,4 +1,5 @@
import base64
import dataclasses
import pathlib
import sys
import tempfile
@@ -7,11 +8,12 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic, Finish
from project_config.settings import DEFAULT_FLOOR, Epic, Finish
from release_plan.todo_table import EXEMPTIONS
from failure import Failure
from plan_store import jira_epic
from plan_store.stores import Plan, Written
from release_plan import ranking
from adf_codec.convert import Refused
from release_plan.release import release_of
@@ -220,6 +222,24 @@ VERSIONS = "https://acme.atlassian.net/rest/api/3/project/ABC/versions"
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under ABC-12 before filing the item again"
FIELDS = {"Release": "0.1.0", "Tagline": "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", "Moves": "1 by 9"}
PROPERTY = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "", "Filed by": "loop"}
RANK = "https://acme.atlassian.net/rest/agile/1.0/issue/rank"
# Goal 1 weighs 1 and goal 2, a maintain goal, 0.5, so under the formula V / 2**S, FIELDS scores 9 / 2 = 4.5.
README = "# P\n\n## Goals\n\n**Void:** code health, since a test project has no code to read.\n\n1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n\n## Audience\n\nMe.\n"
@dataclasses.dataclass(frozen=True)
class Stated:
"""Stands in for the scoring a project's config states, with the goal weights README gives."""
formula: str = "V / 2**S"
bar: float = 1
def read(self) -> ranking.Scoring | Failure:
return ranking.config_scoring(self.formula, self.bar, README, "", "", DEFAULT_FLOOR)
def filed(key: str, moves: str = "1 by 9", s: int = 1, exempt: str = "") -> dict[str, object]:
"""An open child the loop filed, which scores 9 / 2**s with moves "1 by 9"."""
return issue(key, scores=PROPERTY | {"Moves": moves, "S": s, "Exempt": exempt})
class Filing(unittest.TestCase):
@@ -232,25 +252,27 @@ class Filing(unittest.TestCase):
self.created: object = {"id": "10040", "key": "ABC-40"}
self.linked: object = None
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}, "odd", {"name": ["0.1.0"]}, {"name": {"en": "0.1.0"}}]
self.ranked: object = None
self.scoring: Stated | None = Stated()
def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.created to a new issue and self.linked to a new link."""
self.calls.append((method, url, body))
assert authorization == AUTHORIZATION
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions, RANK: self.ranked}.get(url, {"key": "ABC-12"})
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
return adf(markdown)
def add(self, fields: dict[str, str] = FIELDS, detail: str = ""):
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf).add(fields, detail)
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf, scoring=self.scoring).add(fields, detail)
def sent(self, url: str) -> list[object]:
return [body for _, sent_to, body in self.calls if sent_to == url]
def test_files_the_item_as_a_task_under_the_epic_marked_as_the_loops(self):
self.assertEqual(self.add(), Written(40))
self.assertEqual(self.calls, [("GET", VERSIONS, None), ("POST", ISSUES, {
self.assertEqual([call for call in self.calls if call[1] != SEARCH and "/issue/ABC-12" not in call[1]], [("GET", VERSIONS, None), ("POST", ISSUES, {
"fields": {"project": {"key": "ABC"}, "parent": {"key": "ABC-12"}, "issuetype": {"name": "Task"}, "summary": "Count the runs.", "fixVersions": [{"name": "0.1.0"}]},
"properties": [{"key": "plan-item", "value": PROPERTY}],
})])
@@ -303,6 +325,7 @@ class Filing(unittest.TestCase):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Tagline"}), Failure("the item has no tagline"))
def test_an_item_without_moves_files_with_none(self):
self.scoring = Stated(bar=0)
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Moves"}), Written(40))
self.assertEqual(self.sent(ISSUES)[0]["properties"][0]["value"]["Moves"], "") # type: ignore[index]
@@ -367,6 +390,63 @@ class Filing(unittest.TestCase):
self.assertIsInstance(self.add(), Failure)
self.assertEqual(self.calls, [])
def test_an_item_under_the_bar_fails_before_any_request(self):
self.assertEqual(self.add(FIELDS | {"Moves": "2 by 1", "S": "3"}), Failure("the item to file scores 0.1, under the bar 1; don't file it, or mark it with a reason the bar doesn't apply"))
self.assertEqual(self.calls, [])
def test_an_exempt_item_under_the_bar_files(self):
self.assertEqual(self.add(FIELDS | {"Moves": "", "Exempt": "owner"}), Written(40))
def test_an_item_that_names_a_goal_the_goals_file_lacks_fails_before_any_request(self):
self.assertEqual(self.add(FIELDS | {"Moves": "3 by 1"}), Failure("the item to file cites goal 3, which the goals file's ## Goals does not number"))
self.assertEqual(self.calls, [])
def test_an_item_without_every_score_fails_before_any_request(self):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "S"}), Failure("the item to file has no S: score it on L, E, I and S"))
self.assertEqual(self.calls, [])
def test_a_formula_that_does_not_parse_fails_before_any_request(self):
self.scoring = Stated(formula="V +")
self.assertEqual(self.add(), Failure("cannot score the item to file: the formula 'V +' does not parse"))
self.assertEqual(self.calls, [])
def test_a_config_without_a_formula_fails(self):
self.scoring = None
self.assertEqual(self.add(), Failure("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"))
def test_ranks_the_item_just_before_the_first_issue_the_loop_filed_that_scores_lower(self):
# ABC-30 and ABC-33 are a person's, ABC-31 a security finding, and ABC-32 scores as much as the new item.
self.open = [issue("ABC-30"), filed("ABC-31", s=4, exempt="security"), filed("ABC-32"), issue("ABC-33", scores={"L": 1, "E": 1, "I": 1, "S": 4, "Moves": "1 by 1"}), filed("ABC-34", s=2), filed("ABC-35", s=3)]
self.assertEqual(self.add(), Written(40))
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-34"}])
self.assertEqual([method for method, url, _ in self.calls if url == RANK], ["PUT"])
def test_ranks_a_security_finding_just_before_the_first_issue_the_loop_filed_that_isnt_one(self):
self.open = [issue("ABC-30"), filed("ABC-31", exempt="security"), filed("ABC-32"), filed("ABC-33", s=4)]
self.assertEqual(self.add(FIELDS | {"Exempt": "security", "S": "4"}), Written(40))
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-32"}])
def test_leaves_the_item_last_where_no_issue_the_loop_filed_scores_lower(self):
self.open = [issue("ABC-30", scores={}), filed("ABC-31"), filed("ABC-32", s=2, exempt="security")]
self.assertEqual(self.add(), Written(40))
self.assertEqual(self.sent(RANK), [])
def test_a_rank_jira_refuses_leaves_the_item_filed_with_a_note(self):
self.open = [filed("ABC-34", s=2)]
refusals = (
(Failure("PUT /rest/agile/1.0/issue/rank answered 403: Forbidden"), "PUT /rest/agile/1.0/issue/rank answered 403: Forbidden"),
({"entries": [{"issueKey": "ABC-40", "status": 400, "errors": ["Rank is not configured"]}]}, "Rank is not configured"),
)
for answer, reason in refusals:
with self.subTest(answer=answer):
self.ranked = answer
self.assertEqual(self.add(), Written(40, (f"filed ABC-40, but cannot rank it before ABC-34: {reason}; rank it in Jira",)))
def test_an_issue_the_loop_filed_that_does_not_score_leaves_the_item_filed_unranked_with_a_note(self):
self.open = [filed("ABC-34", moves="3 by 1", s=2)]
self.assertEqual(self.add(), Written(40, ("filed ABC-40, but cannot rank it: ABC-34 cites goal 3, which the goals file's ## Goals does not number; rank it in Jira",)))
self.assertEqual(self.sent(RANK), [])
TRANSITIONS = "https://acme.atlassian.net/rest/api/3/issue/ABC-34/transitions"
+21 -2
View File
@@ -8,9 +8,9 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import DEFAULT_FLOOR, Epic, Finish, ProjectConfig, SETTINGS
from project_config.settings import DEFAULT_FLOOR, Epic, Finish, ProjectConfig, Scoring, SETTINGS
from failure import Failure
from record_store.stores import FileStore
from record_store.stores import FileStore, goals_store, store as record_store
from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND
from plan_store.jira_epic import JiraPlan
from plan_store.fakes import MemoryPlan
@@ -215,6 +215,25 @@ class Store(unittest.TestCase):
picked = stores.store(self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_finish=finish))
self.assertEqual(picked.finish_by, finish)
def test_an_epic_scores_by_the_configs_formula_and_bar_and_the_projects_records(self):
config = self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=Scoring("V / 2**S", 1.5), readability_floor=decimal.Decimal("6.5"))
picked = stores.store(config)
self.assertEqual(picked.scoring, stores.StatedScoring(Scoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5")))
class StatedScoring(unittest.TestCase):
def test_weighs_the_goals_the_goals_file_holds(self):
scoring = stores.StatedScoring(Scoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert not isinstance(scoring, Failure), scoring
self.assertEqual((scoring.bar, list(scoring.goals)), (1.5, ["1", "2", "2.1"]))
def test_a_goals_file_that_is_empty_or_cannot_be_read_fails(self):
for goals, reason in ((MemoryStore(), "the record in memory: missing or empty"), (MemoryStore(fails="Jira answered 403"), "Jira answered 403")):
with self.subTest(reason=reason):
read = stores.StatedScoring(Scoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert isinstance(read, Failure), read
self.assertTrue(read.reason.startswith(reason), read.reason)
if __name__ == "__main__":
unittest.main()
+11 -3
View File
@@ -31,6 +31,13 @@ and readme.md, since the reviewers and the rules name those files.
Jira's backlog order, and `project-config plan` prints the setting as the config spells it. Such a
config must set `env-file`, and that file must hold ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN.
Such a config must also set `jira-score-formula` and `jira-score-bar`, which a todo.md states under
## Scoring as `Score` and `Bar`, as `rank_todo.py --help` shows: the formula that scores an item, and
the lowest score at which `todo-item add` files one that isn't exempt. The bar is a bare number:
jira-score-formula = "100 * V / (2**S + 8)"
jira-score-bar = 1
`jira-finish-transition` and `jira-finish-status` are optional settings, set together and only
beside such a plan, since each Jira workflow differs. `todo-item finish` moves an item's issue by
the workflow transition the first names. That transition must lead to the status the second names,
@@ -121,13 +128,14 @@ Exit 1, naming each fault on stderr, where no config names the checkout, or its
setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or
`tooling-on-host` to anything but true or false, sets `notifier` to anything but mattermost or slack or
without `env-file`, sets `jira-finish-transition` or `jira-finish-status` to anything but a name, without the other or
without a `plan` in Jira, or sets `readability-floor` to anything but a number
without a `plan` in Jira, names a Jira `plan` without `jira-score-formula` and `jira-score-bar`, sets
either without such a plan, or the bar to anything but a number, or sets `readability-floor` to anything but a number
from 1 to 10, and where `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
"""
import pathlib
import sys
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
from failure import Failure
from git_cli.git_repo import git, Git
from project_config import templates
@@ -154,7 +162,7 @@ def main(argv: list[str]) -> int:
if argv and argv[0] in config.texts:
print(config.texts[argv[0]])
return 0
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {}), **({JIRA_SCORE_FORMULA: config.jira_scoring.formula, JIRA_SCORE_BAR: f"{config.jira_scoring.bar:g}"} if config.jira_scoring else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
if argv and argv[0] not in paths:
print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr)
return 1
+27 -2
View File
@@ -43,7 +43,11 @@ TOUCH_PREDICTIONS = "touch-predictions"
JIRA_FINISH_TRANSITION = "jira-finish-transition"
JIRA_FINISH_STATUS = "jira-finish-status"
JIRA_FINISH = (JIRA_FINISH_TRANSITION, JIRA_FINISH_STATUS)
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
# Two settings, needed where `plan` names a Jira epic and allowed only there, which a todo.md states under ## Scoring instead: the formula that scores an item, and the bar, the lowest score at which an item is filed. Three readers, seated as the human who writes a client's config, picked the spelling from four candidates: "formula" says the value is no score, and "score-bar" what the bar applies to.
JIRA_SCORE_FORMULA = "jira-score-formula"
JIRA_SCORE_BAR = "jira-score-bar"
JIRA_SCORE = (JIRA_SCORE_FORMULA, JIRA_SCORE_BAR)
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
JIRA = "jira:"
EPIC_SPELLINGS = {
@@ -78,6 +82,13 @@ class Finish:
status: str
@dataclasses.dataclass(frozen=True)
class Scoring:
"""How a plan in Jira scores an item: by formula, such as `100 * V / (2**S + 8)`, with bar the lowest score at which one is filed."""
formula: str
bar: float
@dataclasses.dataclass(frozen=True)
class Page:
"""A Confluence Cloud page: site is its site's address, such as https://acme.atlassian.net, page_id its number, and spelling the setting's value as the config writes it."""
@@ -115,6 +126,8 @@ class ProjectConfig:
notifier: Notifier | None = None
# The config's `jira-finish-transition` and `jira-finish-status`, or None where it sets neither.
jira_finish: Finish | None = None
# The config's `jira-score-formula` and `jira-score-bar`, which it sets where `plan` names an epic.
jira_scoring: Scoring | None = None
# The Confluence page of each record the config keeps on one, by the record's setting.
pages: dict[str, Page] = dataclasses.field(default_factory=dict)
@@ -179,6 +192,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
on_host = values.get(TOOLING_ON_HOST, False)
floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR
finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
formula, bar = values.get(JIRA_SCORE_FORMULA), values.get(JIRA_SCORE_BAR)
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
faults = [
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
@@ -197,6 +211,10 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])),
*(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values),
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_FINISH if name in values and not epics["plan"]),
*(f"`plan` names a Jira epic, so `{name}` must be set, as `project-config --help` shows" for name in JIRA_SCORE if epics["plan"] and name not in values),
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_SCORE if name in values and not epics["plan"]),
*([f"`{JIRA_SCORE_FORMULA}` is {formula!r}, not a formula, such as \"100 * V / (2**S + 8)\""] if JIRA_SCORE_FORMULA in values and not name_of(formula) else []),
*([f"`{JIRA_SCORE_BAR}` is {bar!r}, not a bare number, such as `{JIRA_SCORE_BAR} = 1`"] if JIRA_SCORE_BAR in values and bar_of(bar) is None else []),
*(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)),
*([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []),
*(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))),
@@ -205,7 +223,14 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
# faults names a floor the config misspells.
assert floor is not None
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier, jira_finish=Finish(*finish) if finish else None, pages=pages)
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier, jira_finish=Finish(*finish) if finish else None, jira_scoring=Scoring(typing.cast(str, formula), typing.cast(float, bar_of(bar))) if epics["plan"] else None, pages=pages)
def bar_of(value: object) -> float | None:
"""The bar value spells, an integer or a float; None where it spells none, as for a boolean or TOML's nan or inf, as floor_of says."""
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
return None
return float(value)
def name_of(value: object) -> str | None:
+30 -3
View File
@@ -9,7 +9,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import env_files, Epic, Finish, held, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed
from project_config.settings import env_files, Epic, Finish, held, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, Scoring, SETTINGS, Unnamed
from failure import Failure
from test_env import isolated_env
from project_config.main import located, title_templates
@@ -31,7 +31,8 @@ standards = "~/.claude/skills/larv-review/standards"
"""
JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12"
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n'
JIRA_SCORING = 'jira-score-formula = "100 * V / (2**S + 8)"\njira-score-bar = 1\n'
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n' + JIRA_SCORING
DECISIONS_PAGE = "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761/Decisions"
@@ -320,6 +321,27 @@ class LoadTest(ConfigCase):
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
self.assertIn("`jira-finish-transition` is set, so `plan` must name a Jira epic; `jira-finish-status` is set, so `plan` must name a Jira epic", self.failure())
def test_a_jira_plan_holds_the_formula_and_bar_it_scores_by(self) -> None:
self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5"))
named = load(self.checkout, self.checkout, self.home)
assert isinstance(named, ProjectConfig), named
self.assertEqual(named.jira_scoring, Scoring("100 * V / (2**S + 8)", 0.5))
def test_a_jira_plan_without_a_formula_or_a_bar_fails_naming_each(self) -> None:
self.write("acme", JIRA_CLIENT.replace(JIRA_SCORING, ""))
self.assertIn("`plan` names a Jira epic, so `jira-score-formula` must be set, as `project-config --help` shows; `plan` names a Jira epic, so `jira-score-bar` must be set", self.failure())
def test_a_scoring_setting_misspelt_or_beside_a_plan_in_a_file_fails_naming_it(self) -> None:
config = self.write("acme", JIRA_CLIENT) / "config.toml"
for formula, bar in (('" "', "true"), ("3", '"1"'), ('"V"', "nan")):
with self.subTest(formula=formula, bar=bar):
config.write_text(JIRA_CLIENT.replace(JIRA_SCORING, f"jira-score-formula = {formula}\njira-score-bar = {bar}\n"))
reason = self.failure()
self.assertIn("jira-score-bar` is", reason)
self.assertEqual("jira-score-formula` is" in reason, formula != '"V"')
config.write_text(CLIENT + JIRA_SCORING)
self.assertIn("`jira-score-formula` is set, so `plan` must name a Jira epic; `jira-score-bar` is set, so `plan` must name a Jira epic", self.failure())
def test_a_notifier_that_is_unknown_or_has_no_env_file_fails_naming_it(self) -> None:
self.write("acme", CLIENT + 'env-file = "~/acme.env"\nnotifier = "teams"\n')
self.assertIn("`notifier` is 'teams', not mattermost or slack", self.failure())
@@ -462,7 +484,7 @@ class LoadTest(ConfigCase):
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, language, notifier, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, notifier, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
self.write("acme", CLIENT)
@@ -592,6 +614,11 @@ class ToolTest(ConfigCase):
self.assertEqual(self.run_tool("jira-finish-status").stdout, "Done\n")
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["jira-finish-transition: Mark as done", "jira-finish-status: Done"])
def test_prints_the_formula_and_bar_a_jira_plan_scores_by(self) -> None:
self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5"))
self.assertEqual((self.run_tool("jira-score-formula").stdout, self.run_tool("jira-score-bar").stdout), ("100 * V / (2**S + 8)\n", "0.5\n"))
self.assertIn("jira-score-formula: 100 * V / (2**S + 8)\njira-score-bar: 0.5\n", self.run_tool().stdout)
def test_prints_true_or_false_for_wait_for_approval_and_lists_it_only_where_the_config_sets_it(self) -> None:
folder = self.write("acme", CLIENT)
left_out = self.run_tool("wait-for-approval")
+36 -15
View File
@@ -115,22 +115,30 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, history: str, shape: Shape, floor: decimal.Decimal) -> Scoring | Failure:
goals = ranked_goals(goals_text, decisions)
if isinstance(goals, Failure):
return goals
formula = parse_formula(stated(text, "Score"), variables(shape))
if isinstance(formula, Failure):
return formula
bar = number(stated(text, "Bar"), "the bar")
if isinstance(bar, Failure):
return bar
next_id = stated(text, "Next ID")
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
return scoring_of(stated(text, "Score"), number(stated(text, "Bar"), "the bar"), goals_text, decisions, history, floor, shape=shape, lines=lines, next_id=int(next_id))
def config_scoring(formula: str, bar: float, goals_text: str, decisions: str, history: str, floor: decimal.Decimal) -> Scoring | Failure:
"""The scoring of a plan in Jira, whose formula and bar the project's config states. Jira numbers the issues, so no Next ID applies."""
return scoring_of(formula, bar, goals_text, decisions, history, floor, shape=SHAPE, lines=[], next_id=0)
def scoring_of(formula_text: str | Failure, bar: float | Failure, goals_text: str, decisions: str, history: str, floor: decimal.Decimal, *, shape: Shape, lines: list[str], next_id: int) -> Scoring | Failure:
goals = ranked_goals(goals_text, decisions)
if isinstance(goals, Failure):
return goals
formula = parse_formula(formula_text, variables(shape))
if isinstance(formula, Failure):
return formula
if isinstance(bar, Failure):
return bar
weights = weigh(lines, history, goals, shape, floor)
if isinstance(weights, Failure):
return weights
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
return Scoring(shape, formula, bar, next_id, dict(goals), weights)
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape, floor: decimal.Decimal) -> dict[str, float] | Failure:
@@ -287,19 +295,32 @@ def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
if scoring.shape is OLD_SHAPE:
return item
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
return with_risk(item)
def with_risk(item: Item) -> Item:
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
"""Why the item may not name one of the goals it names, such as one the goals file voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
def item_score(item: Item, scoring: Scoring, name: str) -> float | Failure:
"""The score of an item that holds no R, such as an issue in Jira; refused where it names a goal it may not. name is what a message calls the item."""
if broken := cited_goals_failure(item, scoring, name):
return broken
value = score(scoring.formula, with_risk(item), scoring)
return Failure(f"the formula gives {name} no finite score") if isinstance(value, Failure) else value
def cited_goals_failure(item: Item, scoring: Scoring, name: str = "") -> Failure | None:
"""Why the item may not name one of the goals it names, such as one the goals file voids or does not number; None when it may name each. name is what a message calls the item, `item <ID>` where empty. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
name = name or f"item {item.id}"
if scoring.shape is OLD_SHAPE:
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
return Failure(f"{name} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
for goal, _ in item.moves:
if goal == CODE_HEALTH and goal not in scoring.goals:
return Failure(f"item {item.id} names {CODE_HEALTH}, which the goals file voids; drop it from the item's {MOVES}, or the void from the goals file")
return Failure(f"{name} names {CODE_HEALTH}, which the goals file voids; drop it from the item's {MOVES}, or the void from the goals file")
if goal not in scoring.goals:
return Failure(f"item {item.id} cites goal {goal}, which the goals file's ## Goals does not number")
return Failure(f"{name} cites goal {goal}, which the goals file's ## Goals does not number")
return None
+1 -1
View File
@@ -1279,7 +1279,7 @@ class TodoRankCheck(unittest.TestCase):
def test_a_plan_in_jira_is_not_checked_in_the_checkout_or_the_configs_folder(self):
checkout = self.changed_plan(f"{self.folder}/clone", self.STUB)
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
folder = str(self.config.parent)
git(folder, "init", "-q")
(self.config.parent / "todo.md").write_text("# todo\n")
+1 -1
View File
@@ -62,7 +62,7 @@ class Main(unittest.TestCase):
with tempfile.TemporaryDirectory() as temp:
config = configured(self, pathlib.Path(temp)) / "config.toml"
self.enterContext(contextlib.chdir(temp))
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
todo = pathlib.Path(temp, "todo.md")
todo.write_text(TODO)
for args in ((), (str(todo),), ("--check", str(todo))):
+9 -5
View File
@@ -28,11 +28,15 @@ list and show read only the plan, and print no Score: an item's place in list's
add files the item under the next free ID, with the tagline in bold, and the detail it reads from
stdin, if any. The detail may hold no ## or ### heading.
It prints `Filed item <ID> in <plan>.` It doesn't write anything where ranking fails or scores the item under the bar.
In a Jira epic, add files a Task under the epic, last in the backlog, and <ID> is the new issue's
number. The release must be one of the Jira project's Fix Versions, named as 1.2.0 or v1.2.0 there,
and --exempt security also labels the issue `security`. No bar applies there yet. Where Jira files
the issue and then refuses a --blocked-by link, add still prints `Filed item <ID> …`, and says on
stderr which link to make in Jira.
In a Jira epic, add files a Task under the epic, and <ID> is the new issue's number. The release
must be one of the Jira project's Fix Versions, named as 1.2.0 or v1.2.0 there, and --exempt
security also labels the issue `security`. The item scores by the config's `jira-score-formula`, and
add refuses it under `jira-score-bar` unless it is exempt. Jira then ranks it among the issues the
loop filed only: just before the first that scores lower, or for a security finding, before the
first that isn't one; else it stays last. A person's issues keep their rank, and a security finding
the loop filed comes before every other issue the loop filed. Where Jira files the issue and then
refuses a --blocked-by link or the rank, add still prints `Filed item <ID> …`, and says on stderr
what to do in Jira.
edit sets the cells whose flag is given and leaves the rest; an empty value, as in --blocked-by "",
empties the cell. --detail replaces the detail with the text on stdin, and --clear-detail removes it.
+3 -2
View File
@@ -331,12 +331,13 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
2026-11-14, larv-review, on lilleman's calls of 2026-11-12 and 2026-11-14. Serves goal 1.6: a client's team keeps planning in its own Jira. Valid while a client's plan fits one epic in one Jira project.
- **One epic is one project's plan, and Jira's backlog rank orders it.** The team sets the rank, so the loop's score doesn't break ties and the loop doesn't reorder anything (lilleman, 2026-11-12). An item is an open child issue; one in a done status category is finished.
- **One epic is one project's plan, and Jira's backlog rank orders it.** The team sets the rank, so the loop's score doesn't break ties and the loop never moves an issue once filed (lilleman, 2026-11-12). An item is an open child issue; one in a done status category is finished.
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `plan = "jira:https://<site>/browse/<key>"` over the bare address, a `jira:<key>` beside a `jira-site` key, and a `[plan]` table. Each also picked one pair of env-file keys, `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, for Jira and Confluence over a pair for each, since one account's token opens both.
- **An item's ID stays a whole number: the issue's number in the epic's Jira project.** About 30 modules read an ID as an int, and the `branch` and title templates already spell a ticket's name, as `ABC-{id}`. So the store refuses a child issue from another Jira project, and counts a blocker only among the plan's own items (`bin/plan_store/jira_epic.py`).
- **The scores sit in one issue property, `plan-item`**, which needs no Jira admin (lilleman, 2026-11-12). An issue without it reads as an item nobody scored.
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it.
- **The loop files an item as a Task under the epic, and marks it as its own** (lilleman's calls of 2026-11-12). `"Filed by": "loop"` in the `plan-item` property tells such an issue from one a person filed, whose summary and description the loop never edits. Task is an issue type every Jira Software project template has; a project without it refuses the issue, saying so. The issue takes the project's Fix Version named as the release, with a leading v or without, and the store refuses an item whose release the project has no Fix Version for, before it files anything. A security finding also gets the label `security`, and its text never holds a secret's value. Jira ranks the new issue last, and no bar or goals check applies, until todo.md's item 384 says where a plan in Jira states its formula. Jira takes a blocker's link only after the issue exists, so the store first checks that each blocker is an open child. A link Jira still refuses leaves the issue filed: the write counts as landed, with a note naming the link to make by hand. A failed create says the issue may exist all the same, since a lost answer doesn't tell.
- **The loop files an item as a Task under the epic, and marks it as its own** (lilleman's calls of 2026-11-12). `"Filed by": "loop"` in the `plan-item` property tells such an issue from one a person filed, whose summary and description the loop never edits. Task is an issue type every Jira Software project template has; a project without it refuses the issue, saying so. The issue takes the project's Fix Version named as the release, with a leading v or without, and the store refuses an item whose release the project has no Fix Version for, before it files anything. A security finding also gets the label `security`, and its text never holds a secret's value. Jira takes a blocker's link only after the issue exists, so the store first checks that each blocker is an open child. A link Jira still refuses leaves the issue filed: the write counts as landed, with a note naming the link to make by hand. A failed create says the issue may exist all the same, since a lost answer doesn't tell.
- **The config states the formula and the bar, and the store ranks a new issue among the loop's own** (lilleman, 2026-11-12; the loop chose the rank rule, 2026-11-16). A plan in Jira has no `## Scoring`, so a config whose `plan` names an epic must set `jira-score-formula` and `jira-score-bar`, and fails to load without them, as without a path setting. A bench of readers picked the spelling: three fresh readers, seated as the person who writes a client's `config.toml`, each picked those keys over `jira-score` and `jira-bar`, `score-formula` and `score-bar`, and bare `score` and `bar`. The prefix matches the other Jira-only settings, "formula" says the value is no score, and "score-bar" says what the bar applies to. The store scores the item as `rank_todo.py` scores a row, with the goal weights from the goals file, the decision log and the comprehension history. It refuses an item under the bar that isn't exempt, or one whose Moves names a goal the goals file lacks, before it files anything. Then it ranks the issue just before the first issue the loop filed that scores lower and isn't a security finding; a security finding goes before the first issue the loop filed that isn't one. A person's issues don't count, so the team's rank of each stays as it is. A rank Jira refuses, or an issue of the loop's that no longer scores, leaves the new issue filed and last, with a note to rank it by hand.
- **The store edits and moves only an issue the loop filed, and of an issue a person filed it sets only the scores** (lilleman's calls of 2026-11-12). On its own issue it sets the summary, description, scores and Fix Version in one request, so Jira takes all of an edit or none, and it keeps the label `security` in step with Exempt. Of a person's issue it writes only the `plan-item` property, and a comment: the team's screens don't show the property, so the comment tells the team why the scores changed, and the store refuses the edit without one. The comment's text comes from whoever scores, in the project's `language`. Where Jira takes the edit and then refuses the comment, the edit counts as made, and a note says to post the comment by hand. No edit changes a link, until `todo.md` item 389.
- **The loop may re-score a person's issue that already holds scores, and never moves it.** lilleman's calls of 2026-11-12 cover an issue nobody scored, and say nothing of one that holds scores; larv-review chose on 2026-11-16, through todo item 382. A re-score changes only the loop's own reading of the issue, and not what the person wrote, so it is allowed, with a comment as the first scores need. L, E, I and S are set together, so no issue is left partly scored. The Fix Version says when the team ships the issue, and a release is its team's, so the store refuses the move and `CLAUDE.md` has the worker ask the human to move the issue.
- **`todo-item edit --comment` carries the comment, and a plan in a file takes the flag and keeps no comment**, so one command works in every project, as goal 1.3 asks. A bench of readers picked the spelling: three fresh readers, seated as the consultant who runs the loop in a client's project, each picked `--comment` over `--reason`, `--why` and `--because`. Only it says the text is posted where the team reads it, and `--reason` read as `--exempt`'s reason.
+17
View File
@@ -2311,3 +2311,20 @@ Read most (opens and searches):
- `docs/score-anchors.md` 2
- `bin/release_plan/release.py` 1
- `bin/release_plan/release_standing.py` 1
## Reading cost, chunk c497e828c613, finished 2026-11-16T01:20:21Z
171945 new input tokens before the first commit.
Read most (opens and searches):
- `bin/todo_item/main.py` 8
- `bin/plan_store/jira_epic.py` 6
- `README.md` 5
- `bin/todo_item/test_todo_item.py` 5
- `CLAUDE.md` 4
- `bin/plan_store/stores.py` 4
- `bin/plan_store/test_jira_epic.py` 4
- `docs/decisions.md` 4
- `bin/plan_store/contract.py` 3
- `bin/plan_store/fakes.py` 3