Answer principles round 2: 0 🔴, 2 🟡 (0 misread); workflow-bench hands its effects in as arguments, and no Python file of the repo patches a global
CI / tests (pull_request) Successful in 3m46s

This commit is contained in:
2026-11-19 12:55:35 +01:00
parent cb3135bc8c
commit 762614353c
18 changed files with 335 additions and 231 deletions
+12 -2
View File
@@ -13,11 +13,12 @@ PAGE = 100
MAX_PAGES = 100
# The key of the status category Jira Cloud gives every done status.
DONE = "done"
# How a Failure names an answer in which a field is missing or of another type.
SHAPE = "is not in the shape Jira Cloud's REST API version 3 documents"
# What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue.
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {under} before filing it again"
# What a failed move ends with, for the same reason.
SHAPE = "is not in the shape Jira Cloud's REST API version 3 documents"
PERHAPS_MOVED ="unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again"
PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again"
@dataclasses.dataclass(frozen=True)
@@ -72,6 +73,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 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
status = fields.get("status") if isinstance(fields, dict) else None
category = status.get("statusCategory") if isinstance(status, dict) else None
key = category.get("key") if isinstance(category, dict) else None
return key if isinstance(key, str) else Failure("its status category has no key that is text")
def finishing_transition(site: str, key: str, finish: Finish, authorization: str, http: Http) -> str | Failure:
"""The ID of the transition finish names, as Jira offers it now for the issue named key, which is a plan item or an epic; or why none of those offered finishes it."""
offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None)
+10
View File
@@ -53,5 +53,15 @@ class TheHeadOfAnEntry(unittest.TestCase):
entry_of({"key": "ABC-1", "fields": Faulty()}, "plan")
class TheCategoryOfAnIssuesStatus(unittest.TestCase):
def test_is_the_key_jira_gives_the_category(self):
self.assertEqual(jira.status_category({"fields": {"status": {"statusCategory": {"key": "done"}}}}), "done")
def test_an_answer_in_another_shape_is_a_failure_naming_the_field(self):
for wrong in (["ABC-1"], {}, {"fields": []}, {"fields": {}}, {"fields": {"status": "Done"}}, {"fields": {"status": {}}}, {"fields": {"status": {"statusCategory": "done"}}}, {"fields": {"status": {"statusCategory": {}}}}, {"fields": {"status": {"statusCategory": {"key": 3}}}}):
with self.subTest(wrong=wrong):
self.assertEqual(jira.status_category(wrong), Failure("its status category has no key that is text"))
if __name__ == "__main__":
unittest.main()
+5 -6
View File
@@ -5,7 +5,7 @@ import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped
from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label
from failure import Failure
@@ -127,11 +127,10 @@ class JiraEpic:
answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}?fields=status", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read {self.epic_key}'s status: {answered.reason}")
try:
category = answered["fields"]["status"]["statusCategory"]["key"] # type: ignore[index]
except (KeyError, TypeError) as failure:
return Failure(f"{self.epic_key}'s status is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}")
return bool(category == DONE)
category = status_category(answered)
if isinstance(category, Failure):
return Failure(f"{self.epic_key}'s status {SHAPE}: {category.reason}")
return category == DONE
def close(self, summary: str) -> None | Failure:
if self.finish is None:
+1 -1
View File
@@ -212,7 +212,7 @@ class Jira(Case):
self.assertEqual(self.new_store().close("Shipped."), Failure("posted the summary on ABC-12, but cannot move ABC-12 by 'Mark as done': Jira answered 503; close the epic in Jira rather than posting the summary again"))
def test_says_why_the_epics_status_cannot_be_read(self) -> None:
for answer, reason in ((Failure("Jira answered 503"), "cannot read ABC-12's status: Jira answered 503"), ({"fields": {}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: TypeError('list indices must be integers or slices, not str')")):
for answer, reason in ((Failure("Jira answered 503"), "cannot read ABC-12's status: Jira answered 503"), ({"fields": {}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text"), ({"fields": {"status": {"statusCategory": {"key": 3}}}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text")):
self.jira.answers[("GET", EPIC_STATUS)] = answer
self.assertEqual(self.new_store().closed(), Failure(reason))
+6 -6
View File
@@ -165,8 +165,8 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, own: str
now = start_chunk(epic, chunk if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run)
if isinstance(now, Failure):
return now
if isinstance(now, str):
waits.append(Waits(chunk.issue, now))
if isinstance(now, Waits):
waits.append(now)
else:
windows = now
started.append(chunk.issue)
@@ -176,8 +176,8 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, own: str
return Started(started, sorted(waits, key=lambda wait: order.index(wait.issue)))
def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | str | Failure:
"""Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none, or where the repo's lock cannot be taken. It holds that lock from the check to the start. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo."""
def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | Waits | Failure:
"""Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; a Waits with the reason where its repo takes no chunk now, and a Failure where tmux started none, or where the repo's lock cannot be taken. It holds that lock from the check to the start. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo."""
session = tmux.session_name(tmux.EPIC, epic.key)
handed = {**{name: value for name, value in epic.env.items() if name.startswith(HANDED)}, PARKS: "1"}
command = [str(epic.launcher), CHUNK_FLAG, chunk.issue, epic.key]
@@ -185,13 +185,13 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li
return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(epic.folder), handed, command, windows, False, run)
located = epic.locate(chunk.repo)
if isinstance(located, Failure):
return located.reason
return Waits(chunk.issue, located.reason)
checkout, limit = located
with starting(project_lock(str(checkout), epic.home)) as unlocked:
if unlocked:
return unlocked
if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.home, run)):
return reason
return Waits(chunk.issue, reason)
return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(checkout), handed, command, windows, False, run)
+49 -15
View File
@@ -72,23 +72,45 @@ class PullView:
said: tuple[str, ...]
def text(value: object) -> str:
"""value, which a forge's answer must hold as a string. Raises TypeError where it is none."""
if not isinstance(value, str):
raise TypeError(f"{value!r} is not a string")
# What `held` gives where the answer lacks the key asked for: no text, so the check of the field refuses it.
MISSING = object()
def held(value: object, *path: str) -> object:
"""What a forge's answer holds along path, one key per level; MISSING where a level is no object or lacks its key."""
for key in path:
value = value.get(key, MISSING) if isinstance(value, dict) else MISSING
return value
def pull_view(printed: str) -> PullView | Failure:
"""The pull request that gh printed, with each field checked here, so what decides on it meets no other shape."""
unshaped = Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}")
try:
pull = json.loads(printed)
author = text(pull["author"]["login"])
reviews = tuple(Review(text(review["author"]["login"]), text(review["state"]), text(review["submittedAt"] or ""), text(review["commit"]["oid"]) if review["state"] == CHANGES_REQUESTED else "") for review in pull["reviews"])
commented = tuple(text(comment["createdAt"]) for comment in pull["comments"] if text(comment["author"]["login"]) == author)
return PullView(bool(pull["isDraft"]), text(pull["reviewDecision"] or ""), reviews, tuple(review.submitted_at for review in reviews if review.author == author) + commented)
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}")
except ValueError:
return unshaped
author, draft, decision, listed, comments = held(pull, "author", "login"), held(pull, "isDraft"), held(pull, "reviewDecision") or "", held(pull, "reviews"), held(pull, "comments")
if not isinstance(author, str) or draft is MISSING or not isinstance(decision, str) or not isinstance(listed, list) or not isinstance(comments, list):
return unshaped
reviews = []
for review in listed:
reviewer, state, submitted_at = held(review, "author", "login"), held(review, "state"), held(review, "submittedAt") or ""
commit = held(review, "commit", "oid") if state == CHANGES_REQUESTED else ""
if not isinstance(reviewer, str) or not isinstance(state, str) or not isinstance(submitted_at, str) or not isinstance(commit, str):
return unshaped
reviews.append(Review(reviewer, state, submitted_at, commit))
commented = []
for comment in comments:
commenter, created_at = held(comment, "author", "login"), held(comment, "createdAt")
if not isinstance(commenter, str):
return unshaped
if commenter != author:
continue
if not isinstance(created_at, str):
return unshaped
commented.append(created_at)
return PullView(bool(draft), decision, tuple(reviews), tuple(review.submitted_at for review in reviews if review.author == author) + tuple(commented))
def answered(pull: PullView, head: str) -> bool:
@@ -135,12 +157,24 @@ class Thread:
def threads_read(printed: str) -> tuple[str, tuple[Thread, ...]] | Failure:
"""Who opened the pull request and its review threads, as gh printed THREADS' answer, with each field checked here."""
unshaped = Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}")
try:
pull = json.loads(printed)["data"]["repository"]["pullRequest"]
threads = tuple(Thread(text(thread["path"]), bool(thread["isResolved"]), tuple(text(comment["author"]["login"]) for comment in thread["comments"]["nodes"])) for thread in pull["reviewThreads"]["nodes"])
return text(pull["author"]["login"]), threads
except (ValueError, KeyError, TypeError):
return Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}")
pull = held(json.loads(printed), "data", "repository", "pullRequest")
except ValueError:
return unshaped
author, nodes = held(pull, "author", "login"), held(pull, "reviewThreads", "nodes")
if not isinstance(author, str) or not isinstance(nodes, list):
return unshaped
threads = []
for thread in nodes:
path, resolved, comments = held(thread, "path"), held(thread, "isResolved"), held(thread, "comments", "nodes")
if not isinstance(path, str) or resolved is MISSING or not isinstance(comments, list):
return unshaped
last = tuple(login for comment in comments if isinstance(login := held(comment, "author", "login"), str))
if len(last) != len(comments):
return unshaped
threads.append(Thread(path, bool(resolved), last))
return author, tuple(threads)
def waits(author: str, threads: tuple[Thread, ...]) -> list[str]:
+2 -2
View File
@@ -35,7 +35,7 @@ class ThePullRequestAsViewed(unittest.TestCase):
self.assertEqual(reviews.pull_view(printed), PullView(False, CHANGES_REQUESTED, (Review("rev", CHANGES_REQUESTED, "2026-11-02T10:00:00Z", "abc"), Review("me", "PENDING", "", "")), ("", "2026-11-02T11:00:00Z")))
def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self):
unshaped = ("not json", "[]", json.dumps(PULL | {"reviews": None}), json.dumps(PULL | {"author": None}), json.dumps(PULL | {"reviews": [ASKED | {"commit": None}]}), json.dumps(PULL | {"reviews": [ASKED | {"submittedAt": 7}]}), json.dumps({key: value for key, value in PULL.items() if key != "isDraft"}))
unshaped = ("not json", "[]", json.dumps(PULL | {"reviews": None}), json.dumps(PULL | {"author": None}), json.dumps(PULL | {"reviews": [ASKED | {"commit": None}]}), json.dumps(PULL | {"reviews": [ASKED | {"submittedAt": 7}]}), json.dumps(PULL | {"comments": [{"author": {"login": 7}, "createdAt": "2026-11-02T11:00:00Z"}]}), json.dumps(PULL | {"comments": [{"author": {"login": PULL["author"]["login"]}, "createdAt": None}]}), json.dumps(PULL | {"reviews": [{key: value for key, value in ASKED.items() if key != "submittedAt"}]}), json.dumps({key: value for key, value in PULL.items() if key != "isDraft"}))
for printed in unshaped:
with self.subTest(printed=printed):
self.assertEqual(reviews.pull_view(printed), Failure(f"gh pr view printed no review decision: {printed[:200]}"))
@@ -78,7 +78,7 @@ class TheThreadsThatWait(unittest.TestCase):
self.assertEqual(reviews.waiting_threads("7", lambda args: printed), ["a.py", "b.py"])
def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self):
for printed in ("not json", "{}", json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False}]}}}}})):
for printed in ("not json", "{}", json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False}]}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False, "path": "a.py", "comments": {"nodes": [{"author": {"login": 7}}]}}]}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"path": "a.py", "comments": {"nodes": []}}]}}}}})):
with self.subTest(printed=printed):
self.assertEqual(reviews.waiting_threads("7", lambda args: printed), Failure(f"gh api graphql printed no review threads: {printed[:200]}"))
+3 -2
View File
@@ -20,10 +20,11 @@ def patches(source: str) -> list[int]:
class NoPatchedGlobals(unittest.TestCase):
def test_no_python_file_under_bin_patches_a_global(self):
def test_no_python_file_patches_a_global(self):
# A file not yet staged counts too, so a new suite is checked before its first commit.
listed = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "bin/*.py"],capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
listed = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "*.py"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
self.assertIn("bin/repo_checks/test_no_patched_globals.py", listed)
self.assertIn("workflow-bench/test_bench.py", listed)
patching = {name for name in listed if patches((ROOT / name).read_text(encoding="utf-8"))}
self.assertEqual(patching, set(), "hand the code under test its effect as an argument instead")
+2 -1
View File
@@ -1,9 +1,10 @@
#!/usr/bin/env python3
import pathlib
import sys
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from wait_for import main
sys.exit(main.main(sys.argv[1:]))
sys.exit(main.main(sys.argv[1:], time))
+45 -46
View File
@@ -13,7 +13,6 @@ Exit 0 on the line, 1 on the timeout, bad arguments or a file it cannot read, sa
import pathlib
import re
import sys
import time
import typing
from failure import Failure
@@ -28,25 +27,41 @@ class Clock(typing.Protocol):
def sleep(self, seconds: float) -> None: ...
def text_of(path: pathlib.Path) -> str | None | Failure:
"""What the file holds; None where it doesn't exist."""
try:
return path.read_text(errors="replace")
except FileNotFoundError:
return None
except OSError as error:
return Failure(f"cannot read {path}: {error.strerror}")
def main(argv: list[str], clock: Clock) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
parsed = arguments(argv)
done = parsed if isinstance(parsed, Failure) else waited(*parsed, clock)
if isinstance(done, Failure):
print(f"wait-for: {done.reason}", file=sys.stderr)
return 1
print(done)
return 0
def line_in(text: str, pattern: re.Pattern[str] | None) -> str | None:
"""The first line of text matching pattern, or without one its last line; None where there is none."""
lines = text.splitlines()
if pattern is None:
return lines[-1] if lines else None
return next((line for line in lines if pattern.search(line)), None)
def arguments(argv: list[str]) -> tuple[str, str | None, float] | Failure:
operands = list(argv)
timeout = float(TIMEOUT_SECONDS)
if "--timeout" in operands:
at = operands.index("--timeout")
given = operands[at + 1:at + 2]
if not given or not re.fullmatch(r"[0-9]+(\.[0-9]+)?", given[0]) or float(given[0]) <= 0:
return Failure(f"give --timeout a number of seconds above 0; {USAGE}")
timeout = float(given[0])
del operands[at:at + 2]
if not 1 <= len(operands) <= 2:
return Failure(USAGE)
pattern = operands[1] if len(operands) == 2 else None
if pattern is not None:
try:
re.compile(pattern)
except re.error as error:
return Failure(f"cannot read the pattern `{pattern}`: {error}")
return operands[0], pattern, timeout
def waited(file: str, pattern: str | None, timeout: float, clock: Clock = time) -> str | Failure:
def waited(file: str, pattern: str | None, timeout: float, clock: Clock) -> str | Failure:
path = pathlib.Path(file)
compiled = re.compile(pattern) if pattern is not None else None
deadline = clock.monotonic() + timeout
@@ -72,35 +87,19 @@ def waited(file: str, pattern: str | None, timeout: float, clock: Clock = time)
clock.sleep(min(POLL_SECONDS, left))
def arguments(argv: list[str]) -> tuple[str, str | None, float] | Failure:
operands = list(argv)
timeout = float(TIMEOUT_SECONDS)
if "--timeout" in operands:
at = operands.index("--timeout")
given = operands[at + 1:at + 2]
if not given or not re.fullmatch(r"[0-9]+(\.[0-9]+)?", given[0]) or float(given[0]) <= 0:
return Failure(f"give --timeout a number of seconds above 0; {USAGE}")
timeout = float(given[0])
del operands[at:at + 2]
if not 1 <= len(operands) <= 2:
return Failure(USAGE)
pattern = operands[1] if len(operands) == 2 else None
if pattern is not None:
try:
re.compile(pattern)
except re.error as error:
return Failure(f"cannot read the pattern `{pattern}`: {error}")
return operands[0], pattern, timeout
def text_of(path: pathlib.Path) -> str | None | Failure:
"""What the file holds; None where it doesn't exist."""
try:
return path.read_text(errors="replace")
except FileNotFoundError:
return None
except OSError as error:
return Failure(f"cannot read {path}: {error.strerror}")
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
parsed = arguments(argv)
done = parsed if isinstance(parsed, Failure) else waited(*parsed)
if isinstance(done, Failure):
print(f"wait-for: {done.reason}", file=sys.stderr)
return 1
print(done)
return 0
def line_in(text: str, pattern: re.Pattern[str] | None) -> str | None:
"""The first line of text matching pattern, or without one its last line; None where there is none."""
lines = text.splitlines()
if pattern is None:
return lines[-1] if lines else None
return next((line for line in lines if pattern.search(line)), None)
+1 -1
View File
@@ -116,7 +116,7 @@ class WaitFor(unittest.TestCase):
with self.subTest(argv=argv):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv)
code = main.main(argv, Clock())
self.assertEqual((code, out.getvalue(), err.getvalue()), expected)
def test_arguments_take_the_timeout_anywhere_and_refuse_a_bad_one(self):