Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions plugins/magpie-pr-management/skills/code-review/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ when_to_use: |
produced reviewable PRs; skip when triage has not engaged the PR.
argument-hint: "[pr:N] [area:LBL] [collab:true|false] [team:NAME] [ready] [dry-run]"
capability: capability:review
surface_hash: sha256:5540df0191ad8033
surface_hash: sha256:0411b3fbfc2061d9
license: Apache-2.0
measured_tokens: 4671
measured_tokens: 4673
---
<!-- SPDX-License-Identifier: Apache-2.0
https://www.apache.org/licenses/LICENSE-2.0 -->
Expand Down
24 changes: 11 additions & 13 deletions plugins/magpie-pr-management/skills/code-review/posting.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,18 +88,17 @@ doing it here (Golden rule 9, in [`scope.md`](scope.md)).

## The post

`render` prints `post_command`:
`render` prints `post_command`: `gh api repos/<repo>/pulls/<N>/reviews -X POST --input <payload>`.
The payload carries the event, the body, the head SHA it was drafted against (`commit_id`), and every kept inline thread (`comments`), each placed by `path` + `line` + `side` (RIGHT for an added or context line, LEFT for a removed one) computed from the saved diff; a body-only review (no inline thread survived, or `inline:off`) has no `comments`.
It is a REST call, not a GraphQL mutation, because its path names the repository: the public-surface scrub can only recognise a post to the framework's own repository, and set aside its own tool names, when the command shows where it goes.

- with inline threads: `gh api graphql --input <payload>` — one `addPullRequestReview` mutation carrying the body and every kept thread, each placed by `path` + `line` + `side` (RIGHT for an added or context line, LEFT for a removed one) computed from the saved diff;
- body-only (no inline thread survived, or `inline:off`): `gh pr review <N> --repo <repo> --approve|--request-changes|--comment --body-file <file>`.
It reads the body from a file, never an inline string. Run the command exactly as printed, as a bare command, only after the maintainer confirmed the body.

Both read the body from a file, never an inline string. Run the command exactly as printed, as a bare command, only after the maintainer confirmed the body.
### Confirm the review posted — never re-run it

### Confirm the review posted — never re-run on empty output

`gh pr review` **prints nothing on success.** Empty output is the
expected result, not a failure, and re-running the command because it
"looked like nothing happened" submits the review a second time.
The post prints the new review's JSON, but a failed-looking call
can still have posted it, and re-running the command submits the
review a second time.

That second review cannot be taken back. GitHub's API deletes only
*pending* reviews: `DELETE /repos/{owner}/{repo}/pulls/{n}/reviews/{id}`
Expand All @@ -118,15 +117,14 @@ gh api repos/<repo>/pulls/<N>/reviews

(`render` prints it as `verify_command`; run it as a bare command — a `--jq` filter is fine, a pipe is not — and count the entries whose `user.login` is the viewer.)

Treat a non-zero exit from `gh pr review` as the only failure signal. If
Treat a non-zero exit from the post as the only failure signal. If
the command exits zero, the review is posted — whatever it printed. If
the exit status is genuinely non-zero, re-check with the query above
before any retry, because a partial failure (for example the review
landing but an inline comment being rejected) can still leave a review
behind.

The same applies to `gh pr comment` and to the `addPullRequestReview`
mutation below.
The same applies to `gh pr comment`.

Inline positions are valid only against the head that was diffed; when the Step 8 `guard` reports new commits, re-run Steps 1–7 (`[R]efresh`) or post body-only (`[B]ody-only-now`).

Expand Down Expand Up @@ -250,5 +248,5 @@ When the `dry-run` selector is in effect (see
> *Dry-run mode: would post `<DISP>` review to PR #N. Move on?
> `[Y]es` (default), `[E]dit`, `[S]kip`, `[Q]uit`.*

`gh pr review` is **not invoked**. The session summary lists
`post_command` is **not run**. The session summary lists
the would-have-been dispositions and counts.
4 changes: 2 additions & 2 deletions plugins/magpie-pr-management/skills/stack-review/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ argument-hint: "[pr:N | stack:N] [layers:a-b] [read-budget:LINES] [no-fetch] [dr
capability: capability:review
surface_hash: sha256:f0872f2cf794b6d2
license: Apache-2.0
measured_tokens: 5197
measured_tokens: 5195
---
<!-- SPDX-License-Identifier: Apache-2.0
https://www.apache.org/licenses/LICENSE-2.0 -->
Expand Down Expand Up @@ -180,7 +180,7 @@ Everything you infer from reading is `major` at most, and only after verificatio
**Golden rule 6 — never re-derive what the tool decided.**
Do not re-grade a finding the tool mapped, recompute the verdict, or pick the post target yourself; confirm or drop candidates, then let `verdict` and `post` decide.

**Golden rule 7 — `pr-management-code-review`'s per-PR rules apply by reference:** its [Real-CI guard](../code-review/prerequisites.md#real-ci-guard), [mention policy](../code-review/posting.md#mention-policy), verbatim `COMMENT` [footer](../code-review/posting.md#ai-attribution-footer), full PR URLs, [confirm-never-retry](../code-review/posting.md#confirm-the-review-posted--never-re-run-on-empty-output) posting, and [triage actions](../code-review/scope.md) only pointed at.
**Golden rule 7 — `pr-management-code-review`'s per-PR rules apply by reference:** its [Real-CI guard](../code-review/prerequisites.md#real-ci-guard), [mention policy](../code-review/posting.md#mention-policy), verbatim `COMMENT` [footer](../code-review/posting.md#ai-attribution-footer), full PR URLs, [confirm-never-retry](../code-review/posting.md#confirm-the-review-posted--never-re-run-it) posting, and [triage actions](../code-review/scope.md) only pointed at.

---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,21 +300,18 @@ def inline_comments(
return {"threads": threads, "unanchorable": unanchorable}


REVIEW_MUTATION = """mutation($pullRequestId: ID!, $event: PullRequestReviewEvent!, $body: String, $threads: [DraftPullRequestReviewThread!]) {
addPullRequestReview(input: {pullRequestId: $pullRequestId, event: $event, body: $body, threads: $threads}) {
pullRequestReview { id url }
}
}"""


def review_payload(node_id: str, disposition: str, body: str, threads: list[dict[str, Any]]) -> str:
"""The `gh api graphql --input` document for a review with inline threads."""
variables = {
"pullRequestId": node_id,
"event": disposition,
"body": body,
"threads": [
def review_payload(head_sha: str | None, disposition: str, body: str, threads: list[dict[str, Any]]) -> str:
"""The `POST repos/<repo>/pulls/<N>/reviews` document for a review, inline threads included.

The REST endpoint names the repository in its path, so the public-surface scrub can see
which repository a review goes to; a GraphQL mutation addresses a node id and cannot show it.
`commit_id` pins the review to the head that was read, when the read carries it.
"""
payload: dict[str, Any] = {"event": disposition, "body": body}
if head_sha:
payload["commit_id"] = head_sha
if threads:
payload["comments"] = [
{"path": t["path"], "line": t["line"], "side": t["side"], "body": t["body"]} for t in threads
],
}
return json.dumps({"query": REVIEW_MUTATION, "variables": variables}, indent=2, ensure_ascii=False)
]
return json.dumps(payload, indent=2, ensure_ascii=False)
Original file line number Diff line number Diff line change
Expand Up @@ -697,24 +697,24 @@ def _render(args: argparse.Namespace, cfg: config.Config) -> dict[str, Any]:
body_file.write_text(text + "\n", encoding="utf-8")
hits = review_body.mention_scan(text + "\n" + "\n".join(t["body"] for t in inline["threads"]), allow)
check = review_body.verify_footer(text, variant)
flag = {"APPROVE": "--approve", "REQUEST_CHANGES": "--request-changes", "COMMENT": "--comment"}[
args.disposition
]
repo = cfg.upstream_repo or ""
if not re.fullmatch(r"[A-Za-z0-9._-]+/[A-Za-z0-9._-]+", repo) or not _PR.match(str(args.pr)):
raise SystemExit("pr-management: the upstream repo or PR number is not valid for a command")
payload_file = None
if inline["threads"] and pr.node_id:
payload_file = args.out_dir / f"review-payload-{args.pr}.json"
payload_file.write_text(
review_body.review_payload(pr.node_id, args.disposition, text, inline["threads"]),
encoding="utf-8",
)
command = shlex.join(["gh", "api", "graphql", "--input", str(payload_file)])
else:
command = shlex.join(
["gh", "pr", "review", str(args.pr), "--repo", repo, flag, "--body-file", str(body_file)]
)
# Every review, with or without inline threads, goes through the REST endpoint: its path names
# the repository, which the public-surface scrub needs to recognise the framework's own repo.
payload_file = args.out_dir / f"review-payload-{args.pr}.json"
payload_file.write_text(
review_body.review_payload(
pr.head_sha if _SHA.fullmatch(pr.head_sha or "") else None,
args.disposition,
text,
inline["threads"],
),
encoding="utf-8",
)
command = shlex.join(
["gh", "api", f"repos/{repo}/pulls/{args.pr}/reviews", "-X", "POST", "--input", str(payload_file)]
)
verify = shlex.join(["gh", "api", f"repos/{repo}/pulls/{args.pr}/reviews"])
auto_merge_command = None
if args.auto_merge:
Expand Down Expand Up @@ -760,14 +760,14 @@ def _render(args: argparse.Namespace, cfg: config.Config) -> dict[str, Any]:
"footer": variant,
"footer_verified": check["footer_present"],
"body_file": str(body_file),
"payload_file": str(payload_file) if payload_file else None,
"payload_file": str(payload_file),
"inline_threads": len(inline["threads"]),
"unanchorable": inline["unanchorable"],
"live_mentions": hits,
"post_command": command,
"auto_merge_command": auto_merge_command,
"verify_command": verify,
"verify_note": "Empty output from the post is success. Never re-run it: count the viewer's reviews instead.",
"verify_note": "Never re-run the post, whatever it printed: count the viewer's reviews instead.",
"preview": text.splitlines()[:40],
"docs": ["posting.md"],
}
Expand Down
31 changes: 14 additions & 17 deletions tools/pr-management/src/pr_management/code_review/body.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,21 +300,18 @@ def inline_comments(
return {"threads": threads, "unanchorable": unanchorable}


REVIEW_MUTATION = """mutation($pullRequestId: ID!, $event: PullRequestReviewEvent!, $body: String, $threads: [DraftPullRequestReviewThread!]) {
addPullRequestReview(input: {pullRequestId: $pullRequestId, event: $event, body: $body, threads: $threads}) {
pullRequestReview { id url }
}
}"""


def review_payload(node_id: str, disposition: str, body: str, threads: list[dict[str, Any]]) -> str:
"""The `gh api graphql --input` document for a review with inline threads."""
variables = {
"pullRequestId": node_id,
"event": disposition,
"body": body,
"threads": [
def review_payload(head_sha: str | None, disposition: str, body: str, threads: list[dict[str, Any]]) -> str:
"""The `POST repos/<repo>/pulls/<N>/reviews` document for a review, inline threads included.

The REST endpoint names the repository in its path, so the public-surface scrub can see
which repository a review goes to; a GraphQL mutation addresses a node id and cannot show it.
`commit_id` pins the review to the head that was read, when the read carries it.
"""
payload: dict[str, Any] = {"event": disposition, "body": body}
if head_sha:
payload["commit_id"] = head_sha
if threads:
payload["comments"] = [
{"path": t["path"], "line": t["line"], "side": t["side"], "body": t["body"]} for t in threads
],
}
return json.dumps({"query": REVIEW_MUTATION, "variables": variables}, indent=2, ensure_ascii=False)
]
return json.dumps(payload, indent=2, ensure_ascii=False)
34 changes: 17 additions & 17 deletions tools/pr-management/src/pr_management/code_review/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,24 +697,24 @@ def _render(args: argparse.Namespace, cfg: config.Config) -> dict[str, Any]:
body_file.write_text(text + "\n", encoding="utf-8")
hits = review_body.mention_scan(text + "\n" + "\n".join(t["body"] for t in inline["threads"]), allow)
check = review_body.verify_footer(text, variant)
flag = {"APPROVE": "--approve", "REQUEST_CHANGES": "--request-changes", "COMMENT": "--comment"}[
args.disposition
]
repo = cfg.upstream_repo or ""
if not re.fullmatch(r"[A-Za-z0-9._-]+/[A-Za-z0-9._-]+", repo) or not _PR.match(str(args.pr)):
raise SystemExit("pr-management: the upstream repo or PR number is not valid for a command")
payload_file = None
if inline["threads"] and pr.node_id:
payload_file = args.out_dir / f"review-payload-{args.pr}.json"
payload_file.write_text(
review_body.review_payload(pr.node_id, args.disposition, text, inline["threads"]),
encoding="utf-8",
)
command = shlex.join(["gh", "api", "graphql", "--input", str(payload_file)])
else:
command = shlex.join(
["gh", "pr", "review", str(args.pr), "--repo", repo, flag, "--body-file", str(body_file)]
)
# Every review, with or without inline threads, goes through the REST endpoint: its path names
# the repository, which the public-surface scrub needs to recognise the framework's own repo.
payload_file = args.out_dir / f"review-payload-{args.pr}.json"
payload_file.write_text(
review_body.review_payload(
pr.head_sha if _SHA.fullmatch(pr.head_sha or "") else None,
args.disposition,
text,
inline["threads"],
),
encoding="utf-8",
)
command = shlex.join(
["gh", "api", f"repos/{repo}/pulls/{args.pr}/reviews", "-X", "POST", "--input", str(payload_file)]
)
verify = shlex.join(["gh", "api", f"repos/{repo}/pulls/{args.pr}/reviews"])
auto_merge_command = None
if args.auto_merge:
Expand Down Expand Up @@ -760,14 +760,14 @@ def _render(args: argparse.Namespace, cfg: config.Config) -> dict[str, Any]:
"footer": variant,
"footer_verified": check["footer_present"],
"body_file": str(body_file),
"payload_file": str(payload_file) if payload_file else None,
"payload_file": str(payload_file),
"inline_threads": len(inline["threads"]),
"unanchorable": inline["unanchorable"],
"live_mentions": hits,
"post_command": command,
"auto_merge_command": auto_merge_command,
"verify_command": verify,
"verify_note": "Empty output from the post is success. Never re-run it: count the viewer's reviews instead.",
"verify_note": "Never re-run the post, whatever it printed: count the viewer's reviews instead.",
"preview": text.splitlines()[:40],
"docs": ["posting.md"],
}
Expand Down
17 changes: 12 additions & 5 deletions tools/pr-management/tests/code_review/test_body.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,11 +233,18 @@ def test_inline_comments_and_payload() -> None:
assert result["threads"][0]["body"] == "ask `@bob`" and result["unanchorable"] == [
{"index": 2, "file": "hook.py", "line": 99}
]
payload = json.loads(body.review_payload("PR_1", "COMMENT", "Body", result["threads"]))
assert payload["variables"]["threads"] == [
{"path": "hook.py", "line": 12, "side": "RIGHT", "body": "ask `@bob`"}
]
assert "addPullRequestReview" in payload["query"]
payload = json.loads(body.review_payload("a" * 40, "COMMENT", "Body", result["threads"]))
assert payload == {
"event": "COMMENT",
"body": "Body",
"commit_id": "a" * 40,
"comments": [{"path": "hook.py", "line": 12, "side": "RIGHT", "body": "ask `@bob`"}],
}


def test_a_body_only_review_payload_has_no_comments_and_no_unknown_head() -> None:
payload = json.loads(body.review_payload(None, "APPROVE", "Looks good", []))
assert payload == {"event": "APPROVE", "body": "Looks good"}


def test_an_inline_comment_carries_the_finding_text_not_just_its_rule() -> None:
Expand Down
11 changes: 8 additions & 3 deletions tools/pr-management/tests/code_review/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,12 @@ def test_context_then_disposition_then_render(
"write",
)
assert out["footer_verified"] and out["live_mentions"] == [] and out["inline_threads"] == 1
assert shlex.split(out["post_command"]) == ["gh", "api", "graphql", "--input", out["payload_file"]]
# REST, not GraphQL: the path names the repository, so the public-surface scrub can see the target.
argv = shlex.split(out["post_command"])
assert argv[:2] == ["gh", "api"] and argv[3:] == ["-X", "POST", "--input", out["payload_file"]]
assert argv[2].startswith("repos/") and argv[2].endswith("/pulls/7/reviews")
payload = json.loads(Path(out["payload_file"]).read_text(encoding="utf-8"))
assert payload["event"] == "COMMENT" and len(payload["comments"]) == 1
body = Path(out["body_file"]).read_text()
assert "Apache Product maintainer" in body and "https://example.org/contrib" in body

Expand Down Expand Up @@ -352,7 +357,7 @@ def test_render_auto_picks_valid_curated_sidecar(
)
assert out["footer_verified"] and out["inline_threads"] == 1
payload = json.loads(Path(out["payload_file"]).read_text(encoding="utf-8"))
thread_body = payload["variables"]["threads"][0]["body"]
thread_body = payload["comments"][0]["body"]
assert "Curated maintainer explanation." in thread_body
assert "Original explanation." not in thread_body

Expand Down Expand Up @@ -420,7 +425,7 @@ def test_render_falls_back_when_curated_sidecar_has_mismatched_sha(
)
assert out["footer_verified"] and out["inline_threads"] == 1
payload = json.loads(Path(out["payload_file"]).read_text(encoding="utf-8"))
thread_body = payload["variables"]["threads"][0]["body"]
thread_body = payload["comments"][0]["body"]
assert "Original explanation fallback." in thread_body
assert "Stale sidecar explanation." not in thread_body

Expand Down
6 changes: 4 additions & 2 deletions tools/spec-loop/specs/pr-management-family.md
Original file line number Diff line number Diff line change
Expand Up @@ -530,8 +530,10 @@ same directory; the behaviour is unchanged.
reviews, and `DELETE /repos/{owner}/{repo}/pulls/{n}/reviews/{id}`
answers `422 Can not delete a non-pending pull request review` once
submitted, leaving the body edited down to a pointer as the only
repair. The same rule covers `gh pr comment` and the
`addPullRequestReview` mutation.
repair. The same rule covers `gh pr comment`. Every review is posted
through the REST reviews endpoint (`repos/<repo>/pulls/<N>/reviews`),
never a GraphQL mutation, so the public-surface scrub can see the
target repository.
- **Adversarial second read in code review.** `pr-management-code-review`
offers two paths at Step 5 of `review-flow.md`.
The tool path — `with-reviewers:codex,copilot`, or a resolved
Expand Down
Loading