Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s

This commit is contained in:
2026-11-19 12:42:03 +01:00
parent 8ca612b7a4
commit cb3135bc8c
124 changed files with 1437 additions and 793 deletions
+79 -21
View File
@@ -1,6 +1,6 @@
"""A pull request's review state, read once from its forge: the review decision, whether it is a draft, whether the worker answered the changes a reviewer requested, and the review threads that wait for an answer. chunk-pr and do-epic decide on what this reads, and run no review query of their own."""
import dataclasses
import json
import typing
from failure import Failure
from forge.commands import Forge, gitea, Run
@@ -42,28 +42,64 @@ def answered_decision(pull: str, head: str, run: Run) -> str | None | Failure:
viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision,author,reviews,comments"])
if isinstance(viewed, Failure):
return viewed
view = pull_view(viewed)
if isinstance(view, Failure):
return view
if view.draft:
return None
return ANSWERED if view.decision == CHANGES_REQUESTED and answered(view, head) else view.decision
@dataclasses.dataclass(frozen=True)
class Review:
"""One review of a pull request. GitHub lists a reply in a thread as a review of its own."""
author: str
state: str
# Empty for a review its author has yet to submit.
submitted_at: str
# The commit a review that requested changes was made on; empty for any other review.
commit: str
@dataclasses.dataclass(frozen=True)
class PullView:
"""A pull request as `gh pr view --json isDraft,reviewDecision,author,reviews,comments` prints it."""
draft: bool
# Empty where its branch protection asks for no review.
decision: str
reviews: tuple[Review, ...]
# When its author submitted each review and made each comment. A review the author has yet to submit has no time: it is empty, and answers nobody.
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")
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."""
try:
parsed = json.loads(viewed)
if parsed["isDraft"]:
return None
decision = str(parsed["reviewDecision"] or "")
return ANSWERED if decision == CHANGES_REQUESTED and answered(parsed, head) else decision
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: {viewed.strip()[:200]}")
return Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}")
def answered(pull: dict[str, typing.Any], head: str) -> bool:
"""Whether the worker answered the newest review that requested changes on pull, as `gh pr view --json author,reviews,comments` prints it, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. GitHub lists a reply in a thread as a review of its own. False where it lists no review that requested changes. Raises KeyError or TypeError where pull has another shape.
def answered(pull: PullView, head: str) -> bool:
"""Whether the worker answered the newest review that requested changes on pull, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. False where pull lists no review that requested changes.
The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed.
"""
asked = max((review for review in pull["reviews"] if review["state"] == CHANGES_REQUESTED), key=lambda review: review["submittedAt"], default=None)
asked = max((review for review in pull.reviews if review.state == CHANGES_REQUESTED), key=lambda review: review.submitted_at, default=None)
if asked is None:
return False
author = pull["author"]["login"]
# A review the author has yet to submit has no time, and answers nobody.
said = [review["submittedAt"] or "" for review in pull["reviews"] if review["author"]["login"] == author] + [comment["createdAt"] for comment in pull["comments"] if comment["author"]["login"] == author]
return asked["commit"]["oid"] != head or any(at > asked["submittedAt"] for at in said)
return asked.commit != head or any(at > asked.submitted_at for at in pull.said)
def gitea_decision(pull: str, run: Run) -> str | None | Failure:
@@ -71,10 +107,10 @@ def gitea_decision(pull: str, run: Run) -> str | None | Failure:
viewed = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull}")
if isinstance(viewed, Failure):
return viewed
try:
return None if viewed["title"].upper().startswith(GITEA_DRAFT) else ""
except (KeyError, TypeError, AttributeError):
title = viewed.get("title") if isinstance(viewed, dict) else None
if not isinstance(title, str):
return Failure(f"tea api printed no title of pull request {pull}: {str(viewed)[:200]}")
return None if title.upper().startswith(GITEA_DRAFT) else ""
def waiting_threads(number: str, run: Run) -> list[str] | Failure:
@@ -82,9 +118,31 @@ def waiting_threads(number: str, run: Run) -> list[str] | Failure:
read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"])
if isinstance(read, Failure):
return read
threads = threads_read(read)
if isinstance(threads, Failure):
return threads
return waits(*threads)
@dataclasses.dataclass(frozen=True)
class Thread:
"""One review thread of a pull request."""
path: str
resolved: bool
# Who wrote its last comment; empty for a thread without one.
last: tuple[str, ...]
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."""
try:
pull = json.loads(read)["data"]["repository"]["pullRequest"]
author = pull["author"]["login"]
return sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])})
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: {read.strip()[:200]}")
return Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}")
def waits(author: str, threads: tuple[Thread, ...]) -> list[str]:
"""The files of the threads that wait for an answer from author, who opened the pull request."""
return sorted({thread.path for thread in threads if not thread.resolved and any(last != author for last in thread.last)})