Write a Jira epic's description by section, and change its Goals and Audience only once the human approves

This commit is contained in:
2026-11-18 10:21:21 +01:00
parent 848f40f0c6
commit 9e47b0d566
14 changed files with 444 additions and 30 deletions
+1 -6
View File
@@ -2,16 +2,15 @@
A write never overwrites a teammate's edit: it sends the version after the one held() read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12)."""
import dataclasses
import hashlib
import json
import pathlib
import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, confluence_json, Http, ToAdf, ToMarkdown
from record_store.held import digest_of, Held
from rest_client.json_request import ErrorAnswer
from failure import Failure
from record_store.held import Held
from project_config.settings import Page
# What Confluence answers to a write whose version isn't the one after the version it holds.
@@ -141,7 +140,3 @@ class ConfluencePage:
return Seen(int(held["version"]), str(held["title"]), held.get("digest"))
except (ValueError, KeyError, TypeError) as failure:
return Failure(f"cannot read the version of {self.label} to write over, {over!r}: {failure}")
def digest_of(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
+31 -1
View File
@@ -1,4 +1,4 @@
"""Record stores for tests, held to record_store.contract like every backend."""
"""Record stores and a Jira for tests, held to record_store.contract like every backend."""
import dataclasses
from failure import Failure
@@ -29,3 +29,33 @@ class MemoryStore:
return Failure(f"someone saved {self.label} since version {over}")
self.text, self.version = text, self.version + 1
return Held(text, str(self.version))
class FakeJira:
"""One epic as Jira Cloud's REST API version 3 serves it: a description that is null or a document, and no version a write could check. Its documents hold the text in one paragraph, which fake_adf and fake_markdown convert."""
def __init__(self) -> None:
self.description: dict[str, object] | None = None
self.calls: list[tuple[str, str, str, object]] = []
def http(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url, authorization, body))
if method == "GET":
return {"key": "ABC-12", "fields": {"description": self.description}}
assert isinstance(body, dict)
self.description = body["fields"]["description"]
return None
def teammate_saves(self, text: str) -> None:
self.description = fake_adf(text)
def puts(self) -> list[object]:
return [call[3] for call in self.calls if call[0] == "PUT"]
def fake_adf(text: str) -> dict[str, object]:
return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
def fake_markdown(documents: list[dict[str, object]]) -> list[str]:
return [document["content"][0]["content"][0]["text"] for document in documents] # type: ignore[index]
+6
View File
@@ -1,5 +1,6 @@
"""A record as a read found it or a write left it, which every record backend gives."""
import dataclasses
import hashlib
@dataclasses.dataclass(frozen=True)
@@ -7,3 +8,8 @@ class Held:
"""A record's text as one read found it or one write left it, with its version: what a write over it names, so the write refuses where someone saved the record since. None for a backend whose writes check no version, as a file's."""
text: str
version: str | None = None
def digest_of(text: str) -> str:
"""A fingerprint of a record's text, for a backend whose service keeps no version a write could name."""
return hashlib.sha256(text.encode("utf-8")).hexdigest()
+43 -14
View File
@@ -1,25 +1,29 @@
"""A project's goals and audience kept as the description of one Jira Cloud epic, read over Jira's REST API with the credentials of the config's env-file, and converted by the adf-codec shim.
"""A project's goals and audience kept as the description of one Jira Cloud epic, read and written over Jira's REST API with the credentials of the config's env-file, and converted by the adf-codec shim.
The store only reads: a write, such as `project-record save goals-and-audience`, fails, saying to edit the epic in Jira."""
Jira keeps no version of a description, so the version a read gives is a digest of its markdown, and a write refuses where the description no longer has that digest. A write changes ## Goals or ## Audience only where the store was told the human approved that section in an interrupt (`approved`)."""
import dataclasses
import pathlib
from adf_codec.convert import adfs_to_markdown, Refused
from atlassian.client import basic_auth, Http, jira_json, ToMarkdown
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from record_store.held import digest_of, Held
from project_config.settings import Epic
from failure import Failure
from record_store.held import Held
from text_files.markdown_text import sections
READ_ONLY = "goals and audience kept in Jira are only read: edit the epic's description in Jira"
# The sections of the description a write changes only after the human approves.
APPROVED_SECTIONS = ("Goals", "Audience")
@dataclasses.dataclass(frozen=True)
class EpicDescription:
"""The description of epic as markdown, read with the credentials env_file holds."""
"""The description of epic as markdown, read and written with the credentials env_file holds. approved names the APPROVED_SECTIONS whose change the human approved."""
epic: Epic
env_file: pathlib.Path
http: Http = jira_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
approved: frozenset[str] = frozenset()
@property
def label(self) -> str:
@@ -31,28 +35,53 @@ class EpicDescription:
def read(self) -> str | Failure:
"""The description as markdown; empty where the epic has none."""
held = self.held()
return held if isinstance(held, Failure) else held.text
def held(self) -> Held | Failure:
"""The description as markdown, with its digest as the version a write over it names."""
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
key = self.epic.key
answer = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=description", authorization, None)
answer = self.http("GET", self.url + "?fields=description", authorization, None)
if isinstance(answer, Failure):
return Failure(f"cannot read the epic {key}: {answer.reason}")
fields = answer.get("fields") if isinstance(answer, dict) else None
if not isinstance(fields, dict) or "description" not in fields or not isinstance(fields["description"], dict | None):
return Failure(f"the epic {key} is not in the shape Jira Cloud's REST API version 3 documents: its description field is missing, or neither a document nor null")
if fields["description"] is None:
return ""
return Held("", digest_of(""))
texts = self.to_markdown([fields["description"]])
if isinstance(texts, Refused):
return Failure(f"{key}'s description: {texts.failure.reason}")
if isinstance(texts, Failure):
return Failure(f"cannot convert {key}'s description to markdown: {texts.reason}")
return texts[0]
return Held(texts[0], digest_of(texts[0]))
def held(self) -> Held | Failure:
text = self.read()
return text if isinstance(text, Failure) else Held(text)
@property
def url(self) -> str:
return f"{self.epic.site}/rest/api/3/issue/{self.epic.key}"
def write(self, text: str, over: str | None) -> Held | Failure:
return Failure(READ_ONLY)
"""Replaces the description with text, over the version held() gave. A text that is the description as read sends nothing, since converting it back would drop each block's localId and Jira's spacing paragraphs. The check of over is a read just before the request: Jira would still take an edit made between the two."""
key = self.epic.key
current = self.held()
if isinstance(current, Failure):
return current
if over is not None and current.version != over:
return Failure(f"someone saved the description of {key} since the loop read it, so the loop didn't write it: never overwrite their edit, but ask the human what to do")
if text == current.text:
return current
if unapproved := [name for name in APPROVED_SECTIONS if name not in self.approved and sections(text).get(name) != sections(current.text).get(name)]:
return Failure(f"the write changes ## {unapproved[0]} of {key}'s description, which needs the human's approval in an interrupt first")
document = self.to_adf(text) if text else None
if isinstance(document, Failure):
return Failure(f"cannot convert the text for {key}'s description to ADF: {document.reason}")
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
answer = self.http("PUT", self.url, authorization, {"fields": {"description": document}})
if isinstance(answer, Failure):
return Failure(f"cannot write the description of {key}: {answer.reason}")
return self.held()
+1 -1
View File
@@ -87,7 +87,7 @@ def touch_predictions_store(config: ProjectConfig) -> RecordStore | None:
def goals_store(config: ProjectConfig) -> RecordStore:
"""The store config names for the goals file, which holds ## Goals and ## Audience: a markdown file, or a Jira epic's description, which the store only reads."""
"""The store config names for the goals file, which holds ## Goals and ## Audience: a markdown file, or a Jira epic's description, whose ## Goals and ## Audience the store changes only once the human approved."""
if config.goals_epic is None:
return FileStore(config.paths["goals-and-audience"], config.tracked("goals-and-audience"))
# load refuses a config that names an epic and no env-file.
+119 -4
View File
@@ -9,10 +9,14 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic
from record_store.jira_description import EpicDescription
from failure import Failure
from record_store.fakes import fake_adf, fake_markdown, FakeJira
from record_store.held import Held
from record_store.contract import RecordStoreContract
from adf_codec.convert import Refused
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
URL = "https://acme.atlassian.net/rest/api/3/issue/ABC-12"
GOALS = {"type": "doc", "version": 1, "content": [{"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "Goals"}]}]}
@@ -78,11 +82,122 @@ class EpicDescriptionTest(unittest.TestCase):
self.assertIsInstance(self.store().read(), Failure)
self.assertEqual(self.calls, [])
def test_writing_fails_since_the_store_only_reads(self) -> None:
found = self.store().write("## Goals\n", None)
class WriteCase(unittest.TestCase):
def setUp(self) -> None:
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.jira = FakeJira()
def new_store(self, approved: frozenset[str] = frozenset()) -> EpicDescription:
return EpicDescription(EPIC, self.env, self.jira.http, fake_markdown, fake_adf, approved)
class EpicDescriptionContract(WriteCase, RecordStoreContract):
pass
GOALS_AND_SCORING = "## Goals\n1. **Achieve:** Ship.\n\n## Audience\nMe.\n\n## Scoring\nValue.\n"
class EpicDescriptionWriteTest(WriteCase):
def held(self, text: str) -> Held:
self.jira.teammate_saves(text)
held = self.new_store().held()
assert isinstance(held, Held), held
return held
def test_writes_the_text_as_the_epics_description(self) -> None:
held = self.held(GOALS_AND_SCORING)
text = GOALS_AND_SCORING.replace("Value.", "Value, then risk.")
written = self.new_store().write(text, held.version)
assert isinstance(written, Held), written
self.assertEqual(self.jira.puts(), [{"fields": {"description": fake_adf(text)}}])
put = next(call for call in self.jira.calls if call[0] == "PUT")
self.assertEqual(put[:3], ("PUT", URL, AUTHORIZATION))
self.assertEqual(written, self.new_store().held())
def test_writing_empty_text_clears_the_description(self) -> None:
held = self.held("## Decisions\n- one\n")
self.assertIsInstance(self.new_store().write("", held.version), Held)
self.assertEqual(self.jira.puts(), [{"fields": {"description": None}}])
def test_saving_the_text_a_read_found_leaves_the_description_as_jira_holds_it(self) -> None:
held = self.held(GOALS_AND_SCORING)
before = self.jira.description
self.assertEqual(self.new_store().write(held.text, held.version), held)
self.assertEqual(self.jira.puts(), [])
self.assertIs(self.jira.description, before)
def test_refuses_to_write_where_a_teammate_saved_since_the_read(self) -> None:
held = self.held(GOALS_AND_SCORING)
self.jira.teammate_saves("## Goals\n1. **Achieve:** Their goal.\n")
for text in (held.text, GOALS_AND_SCORING.replace("Value.", "Risk.")):
with self.subTest(text):
found = self.new_store().write(text, held.version)
assert isinstance(found, Failure), found
self.assertIn("someone saved", found.reason)
self.assertIn("ABC-12", found.reason)
self.assertEqual(self.jira.puts(), [])
self.assertEqual(self.new_store().read(), "## Goals\n1. **Achieve:** Their goal.\n")
def test_refuses_to_change_goals_or_audience_before_the_human_approves(self) -> None:
held = self.held(GOALS_AND_SCORING)
changes = [
("Goals", GOALS_AND_SCORING.replace("Ship.", "Ship less.")),
("Audience", GOALS_AND_SCORING.replace("Me.", "Everyone.")),
("Goals", GOALS_AND_SCORING.replace("## Goals\n1. **Achieve:** Ship.\n\n", "")),
]
for name, text in changes:
with self.subTest(name, text=text):
found = self.new_store().write(text, held.version)
assert isinstance(found, Failure), found
self.assertIn(name, found.reason)
self.assertIn("approval", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_refuses_to_add_a_goals_section_before_the_human_approves(self) -> None:
held = self.held("## Scoring\nValue.\n")
found = self.new_store().write("## Goals\n1. **Achieve:** Ship.\n\n## Scoring\nValue.\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("Jira", found.reason)
self.assertEqual(self.calls, [])
self.assertIn("Goals", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_changes_goals_once_the_human_approved_that_section_only(self) -> None:
held = self.held(GOALS_AND_SCORING)
both = GOALS_AND_SCORING.replace("Ship.", "Ship less.").replace("Me.", "Everyone.")
found = self.new_store(frozenset({"Goals"})).write(both, held.version)
assert isinstance(found, Failure), found
self.assertIn("Audience", found.reason)
self.assertNotIn("Goals", found.reason)
self.assertEqual(self.jira.puts(), [])
written = self.new_store(frozenset({"Goals", "Audience"})).write(both, held.version)
self.assertIsInstance(written, Held)
self.assertEqual(self.jira.puts(), [{"fields": {"description": fake_adf(both)}}])
def test_changes_scoring_and_decisions_without_approval(self) -> None:
held = self.held(GOALS_AND_SCORING)
text = GOALS_AND_SCORING.replace("Value.", "Risk.") + "\n## Decisions\n- A choice.\n"
self.assertIsInstance(self.new_store().write(text, held.version), Held)
self.assertEqual(self.jira.puts(), [{"fields": {"description": fake_adf(text)}}])
def test_a_text_the_codec_cannot_convert_is_not_sent(self) -> None:
held = self.held("## Decisions\n- one\n")
store = EpicDescription(EPIC, self.env, self.jira.http, fake_markdown, lambda text: Failure("unsupported markdown"))
found = store.write("## Decisions\n- two\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
self.assertIn("unsupported markdown", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_a_refused_request_fails_naming_the_epic(self) -> None:
held = self.held("## Decisions\n- one\n")
refusing = lambda method, url, authorization, body: Failure("HTTP 403: no permission") if method == "PUT" else self.jira.http(method, url, authorization, body)
found = EpicDescription(EPIC, self.env, refusing, fake_markdown, fake_adf).write("## Decisions\n- two\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
self.assertIn("HTTP 403", found.reason)
if __name__ == "__main__":