Skip to content

Commit ebd6a64

Browse files
mattmilleraiclaude
andauthored
feat(cursor-review): link every auto-approve review to the cursor-approve card (BE-20246) (#412)
* feat(cursor-review): link every auto-approve review to the cursor-approve card (BE-20246) Every review the approver posts (decide's APPROVE, REQUEST_CHANGES and standing block, and approve-external's standing block) now carries a link to the status card. approve-external's approval already linked it. The link has to be in the review when it is posted. Editing a review afterwards would break it: an edited approval reads as stale, and the bot never withdraws an edited request for changes. So on a PR's first round, before any card exists, decide creates a pending card (no_decision/none) just before the review. The round's card replaces it in the same step, by comment id rather than a re-list, so a lagging listing cannot produce a second card. Rounds that post no review create no pending card, and neither does a PR the approver authored. A card that cannot be found or created only costs the review its link. * fix(cursor-approve): give the pending card the start phase's pass/none pair (BE-20246) The pending card a first round creates before its review carried no_decision/none. Agent lane readers escalate that pair to a human: one applies needs-human-review, which withdraws the bot's approvals. A card read in the few seconds before the round's own card replaced it could therefore hand a PR that was being approved to a human. pass/none is the pair render_start already writes while the axes are pending, a round in progress with nothing to do, and every current consumer reads it that way. The text stays "Deciding this round". A test pins the pending card's markers to render_start's non-capped pair. * fix(cursor-review): never strand the pending card a first round creates (BE-20246) Review round on #412: - decide renders the review body before it looks up or creates the card, so a body that fails to render creates no pending card. - A review GitHub refuses as the approver's own PR deletes the pending card it created. An empty or stale --pr-author gets past the up-front check. - A review that could not be withdrawn after the head/base moved, or after a hand-off, now writes a no_decision/human card. The pending card would otherwise keep pointing readers at that review as the decision. - card.ensure looks again after a create that failed ambiguously, so the caller edits a card that did land instead of posting a second one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 095550c commit ebd6a64

8 files changed

Lines changed: 542 additions & 23 deletions

File tree

‎.github/cursor-approve/card.py‎

Lines changed: 68 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@
3333
``capped``) the caller's ``if:`` let through. On a ``pass`` the start phase
3434
then overwrites it with the axes table, as before.
3535
36+
Every review that decide posts links the card (BE-20246), and so must exist
37+
before it: a review cannot be edited afterwards to add the link, because
38+
auto-approve.py treats an edited approval as stale and never withdraws an
39+
edited request for changes. So on a PR's first round decide calls ``ensure``
40+
just before its review, which creates the card from ``render_pending`` when
41+
there is none, and the round's ``render_round`` replaces that in the same step.
42+
3643
Every card carries two machine-readable markers on the lines right after
3744
``CARD_MARKER`` — ``STATE_MARKER`` and ``NEXT_MARKER`` — a stable contract
3845
for agents, documented in docs/callers/cursor-approve.md.
@@ -496,6 +503,28 @@ def _gating_row(finding: dict) -> str:
496503
return f"- **{sev}** — {ref} — {link}" + (f" — gated: {why}" if why else "")
497504

498505

506+
PENDING_TEXT = ("Deciding this round. This card is rewritten with the result in a moment; if it still says "
507+
"this, the card was not updated, so this round's latest auto-approve review is the decision and "
508+
"the workflow run says why.")
509+
510+
511+
def render_pending(round_no, max_rounds, sha: str, run_url: str) -> str:
512+
"""The card decide creates on a PR's first round, just before posting the
513+
review that links to it (BE-20246); ``render_round`` replaces it seconds
514+
later, in the same step.
515+
516+
``pass``/``none``, the pair ``render_start`` writes while the axes are
517+
pending: a round in progress, nothing to do. Agents already read it that
518+
way. Any other pair would ask something of an agent that reads the card
519+
in that window. ``no_decision``/``none`` reads as "escalate to a human",
520+
and a remedy in ``next`` would have it push or relabel under a round that
521+
may be approving.
522+
"""
523+
lines = card_head(STATE_PASS, NEXT_NONE) + [heading(round_no, max_rounds, sha), "", f"**{PENDING_TEXT}**"]
524+
lines += ["", _reviewed_line(sha, run_url)]
525+
return "\n".join(lines) + "\n"
526+
527+
499528
def render_round(round_no, max_rounds, sha: str, state: str, next_step: str, headline: str,
500529
reasons: list, next_text: str, run_url: str, gating=None, threshold: str = "") -> str:
501530
"""The card cursor-review's decide writes for the round it just decided.
@@ -722,13 +751,48 @@ def list_comments(repo: str, pr_number) -> list:
722751
return [c for page in pages for c in page] if pages and isinstance(pages[0], list) else pages
723752

724753

725-
def upsert(repo: str, pr_number, login: str, body: str, entry=None, keep=None) -> dict:
754+
def _comment(text: str) -> dict:
755+
"""A comment write's response, which must name the comment it wrote."""
756+
comment = json.loads(text)
757+
if not isinstance(comment, dict) or comment.get("id") is None:
758+
raise ValueError(f"the comment write returned no comment id ({type(comment).__name__})")
759+
return comment
760+
761+
762+
def ensure(repo: str, pr_number, login: str, body: str) -> tuple:
763+
"""(card, created): this PR's card, created with `body` when there is none.
764+
765+
For a review that links the card, which needs the comment's URL before it
766+
is posted: this file's ``ensure`` phase, and cursor-review's decide on a
767+
PR's first round (BE-20246).
768+
"""
769+
card = find_card(list_comments(repo, pr_number), login)
770+
if card is not None:
771+
return card, False
772+
try:
773+
return _comment(gh(["api", "-X", "POST", f"repos/{repo}/issues/{pr_number}/comments", "--input", "-"],
774+
{"body": body})), True
775+
except (RuntimeError, ValueError):
776+
# A POST that failed ambiguously (a timeout, a reply without an id)
777+
# may have written the card anyway. Look once more, so the caller edits
778+
# that card by id rather than posting a second one.
779+
card = find_card(list_comments(repo, pr_number), login)
780+
if card is None:
781+
raise
782+
return card, True
783+
784+
785+
def upsert(repo: str, pr_number, login: str, body: str, entry=None, keep=None, card=None) -> dict:
726786
"""Edit the existing card in place, or create it when there is none.
727787
728788
The card's axes sentinel is carried into `body` (see `with_axes_history`);
729789
`entry` and `keep` are decide's; `keep` stays None for every other writer.
790+
`card` is a card this run created seconds ago (``ensure``): it is edited
791+
without listing the comments again, since a listing taken that soon after
792+
the write could miss it and post a second card.
730793
"""
731-
card = find_card(list_comments(repo, pr_number), login)
794+
if card is None:
795+
card = find_card(list_comments(repo, pr_number), login)
732796
body = with_axes_history(body, card.get("body") if card is not None else "", entry, keep)
733797
if card is not None:
734798
return json.loads(gh(["api", "-X", "PATCH", f"repos/{repo}/issues/comments/{card['id']}", "--input", "-"],
@@ -795,10 +859,8 @@ def main(argv=None) -> int:
795859
body = render_start(args.round, args.max_rounds, args.commit_sha, axes, args.approve_gate, args.run_url)
796860
elif args.cmd == "ensure":
797861
try:
798-
card = find_card(list_comments(args.repo, args.pr_number), args.login)
799-
if card is None:
800-
body = render_start(args.round, args.max_rounds, args.commit_sha, axes, "", args.run_url)
801-
card = upsert(args.repo, args.pr_number, args.login, body)
862+
card, _ = ensure(args.repo, args.pr_number, args.login,
863+
render_start(args.round, args.max_rounds, args.commit_sha, axes, "", args.run_url))
802864
except (RuntimeError, ValueError) as e:
803865
print(f"::warning::Could not find or create the cursor-approve card: {e}")
804866
return 0

‎.github/cursor-approve/tests/test_card.py‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,20 @@ def test_start_pass(self):
129129
self.assertIn(f"Reviewed commit: `{SHA}`", body)
130130
self.assertNotIn("Next step", body)
131131

132+
def test_pending_asks_nothing_of_an_agent(self):
133+
# BE-20246: on screen for the seconds between a first round's review
134+
# and its real card. It carries the start phase's "round in progress"
135+
# pair, which every agent already reads as nothing to do: the fleet
136+
# escalates `no_decision`/`none` to a human, and a remedy in `next`
137+
# would have an agent push or relabel under a round that may be approving.
138+
body = card.render_pending("1", "5", SHA, RUN)
139+
self.assertEqual(markers(body), markers(card.render_start("1", "5", SHA, ["correctness"], "pass", RUN)))
140+
self.assertEqual(markers(body), ("pass", "none"))
141+
self.assertIn("Cursor approve · round 1 of 5 · `aaaaaaa`", body)
142+
self.assertIn(f"**{card.PENDING_TEXT}**", body)
143+
self.assertIn(f"Reviewed commit: `{SHA}` · [workflow run]({RUN})", body)
144+
self.assertNotIn("Next step", body)
145+
132146
def test_start_capped(self):
133147
body = card.render_start("5", "5", SHA, ["correctness"], "capped", RUN)
134148
self.assertEqual(markers(body), ("capped", "human"))
@@ -393,6 +407,118 @@ def test_no_card_creates_one(self):
393407
self.assertEqual(len(writes), 1)
394408
self.assertEqual(writes[0][0][2], "POST")
395409

410+
def test_a_card_this_run_created_is_edited_without_listing_again(self):
411+
# BE-20246: a listing taken seconds after `ensure` created the card
412+
# could miss it, and upsert would then post a second card.
413+
calls = []
414+
415+
def fake_gh(args, payload=None):
416+
calls.append((args, payload))
417+
return json.dumps({"id": 9})
418+
419+
with mock.patch.object(card, "gh", fake_gh):
420+
card.upsert("o/r", 1, LOGIN, card.CARD_MARKER + "\nnew",
421+
card={"id": 9, "user": {"login": LOGIN}, "body": card.render_pending("1", "5", SHA, RUN)})
422+
self.assertEqual([c[0][:4] for c in calls], [["api", "-X", "PATCH", "repos/o/r/issues/comments/9"]])
423+
self.assertEqual(calls[0][1], {"body": card.CARD_MARKER + "\nnew"})
424+
425+
426+
class Ensure(unittest.TestCase):
427+
"""`ensure`: the card a review links to, created first when there is none."""
428+
429+
URL = "https://github.com/o/r/pull/1#issuecomment-9"
430+
431+
def run_ensure(self, comments, reply=None):
432+
self.writes = []
433+
434+
def fake_gh(args, payload=None):
435+
if "--paginate" in args:
436+
return json.dumps([comments])
437+
self.writes.append((args[2], args[3], payload))
438+
return json.dumps({"id": 9, "html_url": self.URL}) if reply is None else reply
439+
440+
with mock.patch.object(card, "gh", fake_gh):
441+
return card.ensure("o/r", 1, LOGIN, "PENDING")
442+
443+
def test_an_existing_card_is_returned_untouched(self):
444+
existing = {"id": 7, "user": {"login": LOGIN}, "body": card.CARD_MARKER + "\nold",
445+
"html_url": "https://github.com/o/r/pull/1#issuecomment-7"}
446+
self.assertEqual(self.run_ensure([existing]), (existing, False))
447+
self.assertEqual(self.writes, [])
448+
449+
def test_no_card_creates_one_from_the_body_given(self):
450+
found, created = self.run_ensure([])
451+
self.assertTrue(created)
452+
self.assertEqual(found["html_url"], self.URL)
453+
self.assertEqual(self.writes, [("POST", "repos/o/r/issues/1/comments", {"body": "PENDING"})])
454+
455+
def test_a_marker_from_another_author_is_not_the_card(self):
456+
_, created = self.run_ensure([{"id": 7, "user": {"login": "attacker"}, "body": card.CARD_MARKER}])
457+
self.assertTrue(created)
458+
459+
def test_a_reply_without_a_comment_id_is_an_error(self):
460+
for reply in ("null", "[]", "{}", '{"html_url": "https://github.com/o/r/pull/1"}'):
461+
with self.subTest(reply=reply), self.assertRaises(ValueError):
462+
self.run_ensure([], reply=reply)
463+
464+
def test_an_ambiguous_create_that_landed_is_found_and_returned_as_created(self):
465+
# A timeout or a reply without an id may still have written the card:
466+
# the caller must edit that one by id, not post a second.
467+
landed = {"id": 9, "user": {"login": LOGIN}, "body": card.CARD_MARKER + "\nPENDING", "html_url": self.URL}
468+
for failure in (RuntimeError("gh api failed: timed out"), "{}"):
469+
with self.subTest(failure=failure):
470+
listings = iter([[], [landed]])
471+
472+
def fake_gh(args, payload=None, failure=failure):
473+
if "--paginate" in args:
474+
return json.dumps([next(listings)])
475+
if isinstance(failure, Exception):
476+
raise failure
477+
return failure
478+
479+
with mock.patch.object(card, "gh", fake_gh):
480+
self.assertEqual(card.ensure("o/r", 1, LOGIN, "PENDING"), (landed, True))
481+
482+
def test_a_failed_create_with_no_card_after_it_still_raises(self):
483+
def fake_gh(args, payload=None):
484+
if "--paginate" in args:
485+
return json.dumps([[]])
486+
raise RuntimeError("gh api failed: HTTP 502")
487+
488+
with mock.patch.object(card, "gh", fake_gh), self.assertRaises(RuntimeError):
489+
card.ensure("o/r", 1, LOGIN, "PENDING")
490+
491+
def test_the_ensure_phase_prints_the_url_it_found_or_created(self):
492+
for comments, want in (([], self.URL),
493+
([{"id": 7, "user": {"login": LOGIN}, "body": card.CARD_MARKER,
494+
"html_url": "https://github.com/o/r/pull/1#issuecomment-7"}],
495+
"https://github.com/o/r/pull/1#issuecomment-7")):
496+
with self.subTest(want=want), tempfile.TemporaryDirectory() as tmp:
497+
out = os.path.join(tmp, "out")
498+
499+
def fake_gh(args, payload=None, comments=comments):
500+
if "--paginate" in args:
501+
return json.dumps([comments])
502+
return json.dumps({"id": 9, "html_url": self.URL})
503+
504+
with mock.patch.object(card, "gh", fake_gh), mock.patch.dict(os.environ, {"GITHUB_OUTPUT": out}):
505+
self.assertEqual(card.main(["ensure", "--repo", "o/r", "--pr-number", "1", "--login", LOGIN,
506+
"--commit-sha", SHA, "--axes", "correctness"]), 0)
507+
with open(out, encoding="utf-8") as f:
508+
self.assertEqual(f.read(), f"card_url={want}\n")
509+
510+
def test_the_ensure_phase_never_fails_the_job(self):
511+
with tempfile.TemporaryDirectory() as tmp:
512+
out = os.path.join(tmp, "out")
513+
open(out, "w").close()
514+
with mock.patch.object(card, "gh", side_effect=RuntimeError("gh api failed: HTTP 502")), \
515+
mock.patch.dict(os.environ, {"GITHUB_OUTPUT": out}), \
516+
contextlib.redirect_stdout(io.StringIO()):
517+
self.assertEqual(card.main(["ensure", "--repo", "o/r", "--pr-number", "1", "--login", LOGIN,
518+
"--commit-sha", SHA, "--axes", "correctness"]), 0)
519+
with open(out, encoding="utf-8") as f:
520+
self.assertEqual(f.read(), "")
521+
396522

397523
def _secrets_declared(path):
398524
"""Names under `on.workflow_call.secrets` — text-parsed (stdlib only)."""

0 commit comments

Comments
 (0)