You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@magpie.apache.org by po...@apache.org on 2026/10/10 21:33:33 UTC
(magpie) branch main updated: feat(bitbucket): add post-review contract support (#1591)
This is an automated email from the ASF dual-hosted git repository.
potiuk pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/magpie.git
The following commit(s) were added to refs/heads/main by this push:
new 52398ab2 feat(bitbucket): add post-review contract support (#1591)
52398ab2 is described below
commit 52398ab238dae0fe008bee508ffa130be187c627
Author: Kavya Katal <KA...@GMAIL.COM>
AuthorDate: Sun Oct 11 03:03:26 2026 +0530
feat(bitbucket): add post-review contract support (#1591)
* feat(bitbucket): add post-review contract support
* docs(bitbucket): point the approve and request-changes rows at pr review
Both rows still said they do not implement the post_review contract;
pr review now does, so they point callers at it for a review body
together with a verdict.
Generated-by: Claude Opus 5
Claude-Session: https://claude.ai/code/session_01GTPsZ5aEE5bUVYqp47Dpvv
---------
Co-authored-by: Jarek Potiuk <po...@apache.org>
---
tools/bitbucket/README.md | 12 +-
tools/bitbucket/src/magpie_bitbucket/cli.py | 33 ++
tools/bitbucket/src/magpie_bitbucket/cloud.py | 53 +++
tools/bitbucket/src/magpie_bitbucket/datacenter.py | 13 +
tools/bitbucket/src/magpie_bitbucket/normalize.py | 22 ++
tools/bitbucket/tests/test_bitbucket.py | 362 +++++++++++++++++++++
tools/spec-loop/specs/adapters.md | 3 +-
7 files changed, 494 insertions(+), 4 deletions(-)
diff --git a/tools/bitbucket/README.md b/tools/bitbucket/README.md
index 93a22753..f72a51cc 100644
--- a/tools/bitbucket/README.md
+++ b/tools/bitbucket/README.md
@@ -73,6 +73,7 @@ Implemented read-only commands:
- `magpie-bitbucket pr discussion <id>`
- `magpie-bitbucket pr comment <id> --body-file <path>` (Cloud-only write)
- `magpie-bitbucket pr reviews <id>`
+- `magpie-bitbucket pr review <id> --verdict {comment,approve,request-changes} --body-file <path>` (Cloud-only write)
- `magpie-bitbucket pr approve <id>` (Cloud-only write)
- `magpie-bitbucket pr unapprove <id>` (Cloud-only write)
- `magpie-bitbucket pr request-changes <id>` (Cloud-only write)
@@ -155,11 +156,11 @@ surface:
| Change requests | `get_discussion` / `pr discussion <id>` | Partial read-only | Fetches a comments-only discussion subset with pagination. Participants beyond comment authors and unresolved-thread accounting remain incomplete. |
| Change requests | `pr comment <id> --body-file <path>` | Partial write, Cloud only | Creates one top-level Bitbucket Cloud pull-request comment from a caller-supplied body file after explicit caller-side confirmation. Data Center PR comment writes remain unsupported in this command. |
| Change requests | `reviews` supplement / `pr reviews <id>` | Partial read-only | Fetches reviewers, approvals, change-request signals, pending review requests, normalized review events, and an aggregate review decision. This does not post reviews or mutate PR state. |
-| Change requests | `pr approve <id>` / `pr unapprove <id>` | Partial write, Cloud only | Approves or withdraws the authenticated user's approval after explicit caller-side confirmation. Data Center approval writes remain unsupported by these commands. This does not implement the full `post_review` contract surface. |
-| Change requests | `pr request-changes <id>` / `pr remove-request-changes <id>` | Partial write, Cloud only | Requests changes or removes the authenticated user's change request after explicit caller-side confirmation. Data Center change-request writes remain unsupported by these commands. This does not implement the full `post_review` contract surface. |
+| Change requests | `pr approve <id>` / `pr unapprove <id>` | Partial write, Cloud only | Approves or withdraws the authenticated user's approval after explicit caller-side confirmation. Data Center approval writes remain unsupported by these commands. For a review body together with a verdict, use `pr review` (the `post_review` contract). |
+| Change requests | `pr request-changes <id>` / `pr remove-request-changes <id>` | Partial write, Cloud only | Requests changes or removes the authenticated user's change request after explicit caller-side confirmation. Data Center change-request writes remain unsupported by these commands. For a review body together with a verdict, use `pr review` (the `post_review` contract). |
| Change requests | `pr decline <id>` | Partial write, Cloud only | Declines one Bitbucket Cloud pull request after explicit caller-side confirmation. Data Center decline writes remain unsupported by this command. |
| Change requests | `merge_checks` supplement / `pr merge-checks <id>` | Partial read-only | Fetches known read-only merge-check context, including Data Center merge-test results, reported mergeability/conflict fields, status checks, review decision, and normalized blockers. Unknown backend signals remain unknown. This does not merge or mutate PR state. |
-| Change requests | `post_review` | Not implemented | Follow-up work for #606. |
+| Change requests | `post_review` / `pr review <id> --verdict {comment,approve,request-changes} --body-file <path>` | Partial write, Cloud only | Implements the backend-neutral review contract for Bitbucket Cloud after explicit caller-side confirmation. `comment` posts the review body only. `approve` and `request-changes` post the body first and then apply the corresponding Bitbucket verdict. If the second mutation fails after the body was posted, the command fails with an explicit parti [...]
| Change requests | `land` / `pr merge <id> --strategy {merge,squash,rebase} --expected-source-commit <sha>` | Partial write, Cloud only | Submits a Bitbucket Cloud pull-request merge after explicit caller-side confirmation. The caller must run and inspect `pr merge-checks <id>` before invoking this command; `pr merge` does not independently enforce approval, build-status, or merge-check gates. The expected source commit (7–40 hexadecimal characters, rejected before any request otherwise [...]
| Change requests | `pr merge-task-status <id> <task-id>` | Partial read-only, Cloud only | Fetches the status of an asynchronous Bitbucket Cloud pull-request merge task. Pending tasks normalize to `merge_status=submitted`; successful tasks expose `merge_result.merge_commit.hash` as `landed_ref`; failed tasks normalize to `merge_status=failed`. Data Center merge task-status reads remain unsupported. |
| Change requests | `reject` | Not implemented | Follow-up work for #606. |
@@ -215,6 +216,11 @@ uv run --project tools/bitbucket magpie-bitbucket pr comment 123 --body-file /tm
# Fetch pull request review state
uv run --project tools/bitbucket magpie-bitbucket pr reviews 123
+# Post a confirmed backend-neutral review
+uv run --project tools/bitbucket magpie-bitbucket pr review 123 \
+ --verdict approve \
+ --body-file /tmp/review.md
+
# Approve a Bitbucket Cloud pull request after caller-side confirmation
uv run --project tools/bitbucket magpie-bitbucket pr approve 123
diff --git a/tools/bitbucket/src/magpie_bitbucket/cli.py b/tools/bitbucket/src/magpie_bitbucket/cli.py
index 5b4686b5..042498e8 100644
--- a/tools/bitbucket/src/magpie_bitbucket/cli.py
+++ b/tools/bitbucket/src/magpie_bitbucket/cli.py
@@ -134,6 +134,26 @@ def _build_parser() -> argparse.ArgumentParser:
help="Path to the confirmed comment body.",
)
+ pr_review = pr_subparsers.add_parser(
+ "review",
+ help="Post a pull request review after caller-side confirmation.",
+ )
+ pr_review.add_argument(
+ "pull_request_id",
+ help="Pull request ID to review.",
+ )
+ pr_review.add_argument(
+ "--verdict",
+ required=True,
+ choices=("comment", "approve", "request-changes"),
+ help="Review verdict required by the change-request post_review contract.",
+ )
+ pr_review.add_argument(
+ "--body-file",
+ required=True,
+ help="Path to the confirmed review body.",
+ )
+
pr_reviews = pr_subparsers.add_parser("reviews", help="Fetch pull request review-state activity.")
pr_reviews.add_argument("pull_request_id", help="Pull request ID to fetch review state for.")
@@ -301,6 +321,19 @@ def _dispatch(args: argparse.Namespace, config: BitbucketConfig) -> dict[str, An
)
return normalize.created_pull_request_comment(config.kind, raw)
+ if args.subcommand == "pr" and args.pr_action == "review":
+ body = _read_body_file(args.body_file)
+ raw = backend.post_pull_request_review(
+ config,
+ args.pull_request_id,
+ args.verdict,
+ body,
+ )
+ return normalize.posted_pull_request_review(
+ config.kind,
+ raw,
+ )
+
if args.subcommand == "pr" and args.pr_action == "reviews":
raw = backend.get_pull_request_reviews(config, args.pull_request_id)
return normalize.pull_request_reviews(config.kind, raw)
diff --git a/tools/bitbucket/src/magpie_bitbucket/cloud.py b/tools/bitbucket/src/magpie_bitbucket/cloud.py
index 22cfd8bc..ba26edc4 100644
--- a/tools/bitbucket/src/magpie_bitbucket/cloud.py
+++ b/tools/bitbucket/src/magpie_bitbucket/cloud.py
@@ -683,6 +683,59 @@ def create_pull_request_comment(
}
+def post_pull_request_review(
+ config: BitbucketConfig,
+ pull_request_id: str,
+ verdict: str,
+ body: str,
+) -> dict[str, Any]:
+ """Post a confirmed review body and verdict to a Bitbucket Cloud pull request."""
+ if verdict not in {"comment", "approve", "request-changes"}:
+ raise BitbucketError(f"Unsupported pull request review verdict: {verdict}")
+
+ comment_result = create_pull_request_comment(
+ config,
+ pull_request_id,
+ body,
+ )
+
+ comment = comment_result.get("comment")
+
+ if verdict == "comment":
+ return {
+ "pull_request_id": pull_request_id,
+ "verdict": verdict,
+ "comment": comment,
+ "participant": None,
+ }
+
+ try:
+ if verdict == "approve":
+ verdict_result = approve_pull_request(
+ config,
+ pull_request_id,
+ )
+ else:
+ verdict_result = request_pull_request_changes(
+ config,
+ pull_request_id,
+ )
+ except BitbucketError as exc:
+ raise BitbucketError(
+ "Bitbucket pull request review body was posted, but the "
+ f"{verdict} verdict failed. Inspect `pr discussion {pull_request_id}` "
+ f"and `pr reviews {pull_request_id}` before retrying to avoid "
+ "duplicating the review comment."
+ ) from exc
+
+ return {
+ "pull_request_id": pull_request_id,
+ "verdict": verdict,
+ "comment": comment,
+ "participant": verdict_result.get("participant"),
+ }
+
+
def get_pull_request_discussion(config: BitbucketConfig, pull_request_id: str) -> dict[str, Any]:
"""Fetch pull request comments from Bitbucket Cloud."""
workspace = quote_path(require(config.workspace, "BITBUCKET_WORKSPACE"))
diff --git a/tools/bitbucket/src/magpie_bitbucket/datacenter.py b/tools/bitbucket/src/magpie_bitbucket/datacenter.py
index 12183689..14f0c595 100644
--- a/tools/bitbucket/src/magpie_bitbucket/datacenter.py
+++ b/tools/bitbucket/src/magpie_bitbucket/datacenter.py
@@ -451,6 +451,19 @@ def create_pull_request_comment(
raise BitbucketError(msg)
+def post_pull_request_review(
+ config: BitbucketConfig,
+ pull_request_id: str,
+ verdict: str,
+ body: str,
+) -> dict[str, Any]:
+ """Reject post-review writes for Bitbucket Data Center for now."""
+ _ = (config, pull_request_id, verdict, body)
+ raise BitbucketError(
+ "Bitbucket Data Center pull request post-review writes are not supported by this command yet"
+ )
+
+
def get_pull_request_discussion(config: BitbucketConfig, pull_request_id: str) -> dict[str, Any]:
"""Fetch pull request activities from Bitbucket Data Center."""
project_key = quote_path(require(config.project_key, "BITBUCKET_PROJECT_KEY"))
diff --git a/tools/bitbucket/src/magpie_bitbucket/normalize.py b/tools/bitbucket/src/magpie_bitbucket/normalize.py
index 8f15042f..c7c9cf6f 100644
--- a/tools/bitbucket/src/magpie_bitbucket/normalize.py
+++ b/tools/bitbucket/src/magpie_bitbucket/normalize.py
@@ -277,6 +277,28 @@ def created_pull_request_comment(
}
+def posted_pull_request_review(
+ kind: str,
+ raw: dict[str, Any],
+) -> dict[str, Any]:
+ """Normalize a posted pull-request review."""
+ comment = raw.get("comment")
+ normalized_comment = _cloud_comment(comment) if kind == "cloud" and isinstance(comment, dict) else {}
+
+ participant = raw.get("participant")
+
+ return {
+ "ok": bool(normalized_comment),
+ "backend": "bitbucket-cloud" if kind == "cloud" else "bitbucket-datacenter",
+ "operation": "pull-request-review",
+ "pull_request_id": _string(raw.get("pull_request_id")),
+ "verdict": _string(raw.get("verdict")),
+ "comment": normalized_comment,
+ "participant": participant if isinstance(participant, dict) else None,
+ "raw": raw,
+ }
+
+
def pull_request_discussion(kind: str, raw: dict[str, Any]) -> dict[str, Any]:
"""Normalize pull request discussion/comments from Bitbucket."""
values = raw.get("values")
diff --git a/tools/bitbucket/tests/test_bitbucket.py b/tools/bitbucket/tests/test_bitbucket.py
index 51e3bc09..83f96832 100644
--- a/tools/bitbucket/tests/test_bitbucket.py
+++ b/tools/bitbucket/tests/test_bitbucket.py
@@ -48,6 +48,7 @@ from magpie_bitbucket.normalize import (
issue_comments,
issue_list,
merged_pull_request,
+ posted_pull_request_review,
pull_request,
pull_request_approval,
pull_request_change_request,
@@ -4279,3 +4280,364 @@ def test_cli_pr_merge_task_status_datacenter_fails_without_request(
stderr = capsys.readouterr().err
assert "merge task-status reads are not supported" in stderr
+
+
+def test_cloud_post_pull_request_review_comment_only(
+ cloud_env: None,
+) -> None:
+ with (
+ patch(
+ "magpie_bitbucket.cloud.create_pull_request_comment",
+ return_value={
+ "pull_request_id": "7",
+ "comment": {
+ "id": 601,
+ "content": {"raw": "Review body."},
+ "deleted": False,
+ },
+ },
+ ) as mock_comment,
+ patch("magpie_bitbucket.cloud.approve_pull_request") as mock_approve,
+ patch("magpie_bitbucket.cloud.request_pull_request_changes") as mock_request_changes,
+ ):
+ result = cloud.post_pull_request_review(
+ load_config(),
+ "7",
+ "comment",
+ "Review body.",
+ )
+
+ mock_comment.assert_called_once_with(
+ load_config(),
+ "7",
+ "Review body.",
+ )
+ mock_approve.assert_not_called()
+ mock_request_changes.assert_not_called()
+
+ assert result["verdict"] == "comment"
+ assert result["comment"]["id"] == 601
+ assert result["participant"] is None
+
+
+def test_cloud_post_pull_request_review_approve_posts_body_before_verdict(
+ cloud_env: None,
+) -> None:
+ order: list[str] = []
+
+ def create_comment(*args: Any) -> dict[str, Any]:
+ order.append("comment")
+ return {
+ "pull_request_id": "7",
+ "comment": {
+ "id": 601,
+ "content": {"raw": "LGTM."},
+ "deleted": False,
+ },
+ }
+
+ def approve(*args: Any) -> dict[str, Any]:
+ order.append("approve")
+ return {
+ "pull_request_id": "7",
+ "participant": {
+ "approved": True,
+ "state": "approved",
+ },
+ }
+
+ with (
+ patch(
+ "magpie_bitbucket.cloud.create_pull_request_comment",
+ side_effect=create_comment,
+ ),
+ patch(
+ "magpie_bitbucket.cloud.approve_pull_request",
+ side_effect=approve,
+ ),
+ ):
+ result = cloud.post_pull_request_review(
+ load_config(),
+ "7",
+ "approve",
+ "LGTM.",
+ )
+
+ assert order == ["comment", "approve"]
+ assert result["verdict"] == "approve"
+ assert result["participant"]["approved"] is True
+
+
+def test_cloud_post_pull_request_review_request_changes(
+ cloud_env: None,
+) -> None:
+ with (
+ patch(
+ "magpie_bitbucket.cloud.create_pull_request_comment",
+ return_value={
+ "pull_request_id": "7",
+ "comment": {
+ "id": 601,
+ "content": {"raw": "Please fix this."},
+ "deleted": False,
+ },
+ },
+ ),
+ patch(
+ "magpie_bitbucket.cloud.request_pull_request_changes",
+ return_value={
+ "pull_request_id": "7",
+ "participant": {
+ "approved": False,
+ "state": "changes_requested",
+ },
+ },
+ ) as mock_request_changes,
+ ):
+ result = cloud.post_pull_request_review(
+ load_config(),
+ "7",
+ "request-changes",
+ "Please fix this.",
+ )
+
+ mock_request_changes.assert_called_once()
+ assert result["verdict"] == "request-changes"
+ assert result["participant"]["state"] == "changes_requested"
+
+
+def test_cloud_post_pull_request_review_rejects_invalid_verdict_before_write(
+ cloud_env: None,
+) -> None:
+ with (
+ patch("magpie_bitbucket.cloud.create_pull_request_comment") as mock_comment,
+ patch("magpie_bitbucket.cloud.approve_pull_request") as mock_approve,
+ ):
+ with pytest.raises(
+ BitbucketError,
+ match="Unsupported pull request review verdict",
+ ):
+ cloud.post_pull_request_review(
+ load_config(),
+ "7",
+ "dismiss",
+ "Review body.",
+ )
+
+ mock_comment.assert_not_called()
+ mock_approve.assert_not_called()
+
+
+def test_cloud_post_pull_request_review_reports_partial_failure(
+ cloud_env: None,
+) -> None:
+ with (
+ patch(
+ "magpie_bitbucket.cloud.create_pull_request_comment",
+ return_value={
+ "pull_request_id": "7",
+ "comment": {
+ "id": 601,
+ "content": {"raw": "LGTM."},
+ "deleted": False,
+ },
+ },
+ ),
+ patch(
+ "magpie_bitbucket.cloud.approve_pull_request",
+ side_effect=BitbucketError("approve failed"),
+ ),
+ pytest.raises(
+ BitbucketError,
+ match="review body was posted",
+ ) as exc,
+ ):
+ cloud.post_pull_request_review(
+ load_config(),
+ "7",
+ "approve",
+ "LGTM.",
+ )
+
+ assert "before retrying" in str(exc.value)
+
+
+def test_datacenter_post_pull_request_review_unsupported(
+ datacenter_env: None,
+) -> None:
+ with pytest.raises(
+ BitbucketError,
+ match="Data Center pull request post-review writes are not supported",
+ ):
+ datacenter.post_pull_request_review(
+ load_config(),
+ "9",
+ "approve",
+ "LGTM.",
+ )
+
+
+def test_normalize_posted_pull_request_review() -> None:
+ normalized = posted_pull_request_review(
+ "cloud",
+ {
+ "pull_request_id": "7",
+ "verdict": "approve",
+ "comment": {
+ "id": 601,
+ "content": {"raw": "LGTM."},
+ "user": {"display_name": "Alice"},
+ "deleted": False,
+ },
+ "participant": {
+ "approved": True,
+ "state": "approved",
+ },
+ },
+ )
+
+ assert normalized["ok"] is True
+ assert normalized["backend"] == "bitbucket-cloud"
+ assert normalized["operation"] == "pull-request-review"
+ assert normalized["pull_request_id"] == "7"
+ assert normalized["verdict"] == "approve"
+ assert normalized["comment"]["body"] == "LGTM."
+ assert normalized["participant"]["approved"] is True
+
+
+@patch("magpie_bitbucket.cloud.post_pull_request_review")
+def test_cli_pr_review_cloud(
+ mock_post_review: MagicMock,
+ cloud_env: None,
+ tmp_path: Path,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ body_file = tmp_path / "review.md"
+ body_file.write_text("LGTM.", encoding="utf-8")
+
+ mock_post_review.return_value = {
+ "pull_request_id": "7",
+ "verdict": "approve",
+ "comment": {
+ "id": 601,
+ "content": {"raw": "LGTM."},
+ "user": {"display_name": "Alice"},
+ "deleted": False,
+ },
+ "participant": {
+ "approved": True,
+ "state": "approved",
+ },
+ }
+
+ exit_code = main(
+ [
+ "pr",
+ "review",
+ "7",
+ "--verdict",
+ "approve",
+ "--body-file",
+ str(body_file),
+ ]
+ )
+
+ assert exit_code == 0
+
+ mock_post_review.assert_called_once_with(
+ load_config(),
+ "7",
+ "approve",
+ "LGTM.",
+ )
+
+ output = json.loads(capsys.readouterr().out)
+
+ assert output["ok"] is True
+ assert output["operation"] == "pull-request-review"
+ assert output["verdict"] == "approve"
+ assert output["comment"]["body"] == "LGTM."
+ assert output["participant"]["approved"] is True
+
+
+@patch("magpie_bitbucket.cloud.post_pull_request_review")
+def test_cli_pr_review_rejects_empty_body_before_write(
+ mock_post_review: MagicMock,
+ cloud_env: None,
+ tmp_path: Path,
+) -> None:
+ body_file = tmp_path / "empty-review.md"
+ body_file.write_text(" ", encoding="utf-8")
+
+ with pytest.raises(
+ BitbucketError,
+ match="Comment body file must not be empty",
+ ):
+ main(
+ [
+ "pr",
+ "review",
+ "7",
+ "--verdict",
+ "approve",
+ "--body-file",
+ str(body_file),
+ ]
+ )
+
+ mock_post_review.assert_not_called()
+
+
+@patch("magpie_bitbucket.client.urllib.request.build_opener")
+def test_cli_pr_review_datacenter_fails_without_request(
+ mock_build_opener: MagicMock,
+ datacenter_env: None,
+ tmp_path: Path,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ body_file = tmp_path / "review.md"
+ body_file.write_text("LGTM.", encoding="utf-8")
+
+ exit_code = package_main(
+ [
+ "pr",
+ "review",
+ "9",
+ "--verdict",
+ "approve",
+ "--body-file",
+ str(body_file),
+ ]
+ )
+
+ assert exit_code == 1
+ mock_build_opener.assert_not_called()
+
+ stderr = capsys.readouterr().err
+ assert "post-review writes are not supported" in stderr
+
+
+@patch("magpie_bitbucket.cloud.post_pull_request_review")
+def test_cli_pr_review_rejects_invalid_verdict_before_write(
+ mock_post_review: MagicMock,
+ cloud_env: None,
+ tmp_path: Path,
+) -> None:
+ body_file = tmp_path / "review.md"
+ body_file.write_text("Review body.", encoding="utf-8")
+
+ with pytest.raises(SystemExit) as exc:
+ main(
+ [
+ "pr",
+ "review",
+ "7",
+ "--verdict",
+ "dismiss",
+ "--body-file",
+ str(body_file),
+ ]
+ )
+
+ assert exc.value.code == 2
+ mock_post_review.assert_not_called()
diff --git a/tools/spec-loop/specs/adapters.md b/tools/spec-loop/specs/adapters.md
index a002784d..5333cd42 100644
--- a/tools/spec-loop/specs/adapters.md
+++ b/tools/spec-loop/specs/adapters.md
@@ -314,7 +314,8 @@ uv run --all-packages --group dev pytest tools/github-rollup/tests
the calling skill must obtain explicit user confirmation before invoking a
mutation. The bridge executes only the confirmed action; current write
coverage is Bitbucket Cloud issue-comment creation, Bitbucket Cloud
- pull-request comment creation, and Bitbucket Cloud pull-request
+ pull-request comment creation, backend-neutral `post_review` through
+ comment/approve/request-changes, and Bitbucket Cloud pull-request
approve/unapprove, request-changes/remove-request-changes, decline, and
strategy-aware merge actions pinned to a caller-confirmed source commit
(7–40 hex characters); gate checks before a merge are the caller's