Skip to content
Merged
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: 3 additions & 1 deletion .github/workflows/ai_review.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ jobs:
env:
GH_TOKEN: ${{ secrets.PAT_TOKEN }}
GH_REPO: ${{ github.repository }}
run: python3 .github/workflows/scripts/ai_review.py prepare
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
python3 .github/workflows/scripts/ai_review.py prepare

- uses: actions/checkout@v7
if: steps.prepare.outputs.review == 'true'
Expand Down
42 changes: 25 additions & 17 deletions .github/workflows/scripts/ai_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import sys
import tempfile
import time
from contextlib import suppress
from dataclasses import asdict, dataclass, field
from pathlib import Path

Expand Down Expand Up @@ -317,7 +318,7 @@ def authorize(self, event_name: str, event: dict) -> bool:
"Permission denied. Only the PR author or a maintainer with write access can request a review.",
)
return False
elif command != "push" and not self.can_write(actor):
elif command in ("/ai-review-stop", "/ai-review-waive") and not self.can_write(actor):
self.feedback(event, "Permission denied. This action requires repository write access.")
return False

Expand All @@ -327,7 +328,7 @@ def authorize(self, event_name: str, event: dict) -> bool:
if command not in ("stop", "/ai-review-stop") and not enabled:
if command != "push":
self.feedback(
event, "AI review is not enabled. Ask an allowlisted maintainer to add the `ai-review` label."
event, "AI review is not enabled. Ask an allowlisted reviewer to add the `ai-review` label."
)
return False

Expand All @@ -351,7 +352,7 @@ def authorize(self, event_name: str, event: dict) -> bool:
self.remove_labels(pull, AI_REVIEW_LABEL, AI_REVIEW_PASSED_LABEL)
message = (
"Review labels removed. The bot will update the summary. To restart, wait for this run to finish, "
"then ask an allowlisted maintainer to reapply the `ai-review` label."
"then ask an allowlisted reviewer to reapply the `ai-review` label."
)
elif command == "/ai-review-waive":
message = "Waiver request accepted. The bot will check the findings and commit before applying it."
Expand Down Expand Up @@ -400,9 +401,7 @@ def prepare(self, event_name: str, event: dict, run_id: str) -> dict | None:
if command == "stop" and enabled:
return None # The label has already been reapplied to restart.
if not stopping and not enabled:
self.feedback(
event, "AI review is not enabled. Ask an allowlisted maintainer to add the `ai-review` label."
)
self.feedback(event, "AI review is not enabled. Ask an allowlisted reviewer to add the `ai-review` label.")
return None

# Read the published summary to handle stops, session restarts and waivers.
Expand All @@ -425,9 +424,7 @@ def prepare(self, event_name: str, event: dict, run_id: str) -> dict | None:
self.state.round = self.state.total = 0
self.state.session_run_id = run_id
elif self.state.status == "stopped":
self.feedback(
event, "AI review is stopped. Ask an allowlisted maintainer to reapply the `ai-review` label."
)
self.feedback(event, "AI review is stopped. Ask an allowlisted reviewer to reapply the `ai-review` label.")
return None

if command == "/ai-review-waive":
Expand All @@ -447,26 +444,24 @@ def prepare(self, event_name: str, event: dict, run_id: str) -> dict | None:
self.feedback(
event,
f"Reached the {MAX_TOTAL_ROUNDS}-round limit for this session. "
"Ask an allowlisted maintainer to reapply the `ai-review` label to reset the counts. "
"Ask an allowlisted reviewer to reapply the `ai-review` label to reset the counts. "
"Pushing new commits does not reset the session count.",
)
return None
if self.state.round >= MAX_ROUNDS_PER_HEAD:
self.feedback(
event,
f"Reached the {MAX_ROUNDS_PER_HEAD}-round limit for this commit. Push changes and comment `/ai-review` "
"again, or ask an allowlisted maintainer to reapply the `ai-review` label to reset the counts.",
"again, or ask an allowlisted reviewer to reapply the `ai-review` label to reset the counts.",
)
return None

# Mark the review pending and build its diff. Publishing the summary will count the round.
# Build the review inputs. Publishing the summary will count the round.
self.remove_labels(pull, AI_REVIEW_PASSED_LABEL)
self.state.status = "reviewing"
self.state.coverage_complete = False
self.state.requires_human = False

self.commit_status("pending")

for attempt in range(1, GIT_FETCH_MAX_ATTEMPTS + 1):
try:
git(self.workspace, "fetch", "--no-tags", "origin", self.state.base, self.state.head)
Expand Down Expand Up @@ -538,10 +533,11 @@ def publish(self, request: dict, output: str):
pull = self.pull()
if pull["state"] != "open" or AI_REVIEW_LABEL not in {label["name"] for label in pull["labels"]}:
print("Review stopped or PR closed; no result published.")
self.state.status = "stopped"
self.commit_status("error")
return

self.summary_comment_id = request["comment_id"]
self.state = State.from_dict(request["state"])
self.state.round += 1
self.state.total += 1

Expand Down Expand Up @@ -597,6 +593,9 @@ def publish_status(self):
or AI_REVIEW_LABEL not in {label["name"] for label in pull["labels"]}
or (pull["base"]["sha"], pull["head"]["sha"]) != (self.state.base, self.state.head)
):
# Finish the status on the reviewed commit without changing the PR's labels.
self.state.status = "discarded"
self.commit_status("error")
return

if self.state.status == "passed":
Expand Down Expand Up @@ -788,8 +787,17 @@ def main() -> int:
if args.phase == "review":
request = json.loads(args.request.read_text())
orchestrator = Orchestrator(workspace, request["pr"])
output = run_agent(workspace, request)
orchestrator.publish(request, output)
orchestrator.state = State.from_dict(request["state"])
orchestrator.commit_status("pending")
try:
output = run_agent(workspace, request)
orchestrator.publish(request, output)
except Exception:
orchestrator.state.status = "error"
# gh already logs API errors. Keep the original review exception if reporting also fails.
with suppress(subprocess.CalledProcessError):
orchestrator.commit_status("error")
raise
return 0

event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
Expand Down
55 changes: 41 additions & 14 deletions .github/workflows/scripts/test_ai_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def commit(path, content):

kb = repo / ".github/agent-review"
shutil.copytree(Path(__file__).resolve().parents[2] / "agent-review", kb)
(kb / "allowlist.txt").write_text("maintainer # pilot reviewer\n")
(kb / "allowlist.txt").write_text("maintainer # pilot reviewer\npilot-triager\n")
return SimpleNamespace(repo=repo, common=common, base=base, head=head, next_head=next_head)


Expand Down Expand Up @@ -99,7 +99,10 @@ def api(self, endpoint, *args, payload=None, anchor_fallback=False):
if path == "pulls/7":
return self.pull | {"labels": [{"name": name} for name in self.labels]}
if path.startswith("collaborators/"):
return {"permission": "write" if path.split("/")[1] in {"maintainer", "writer"} else "read"}
actor = path.split("/")[1]
if actor in {"pilot-triager", "unlisted-triager"}:
return {"permission": "read", "role_name": "triage"}
return {"permission": "write" if actor in {"maintainer", "writer"} else "read"}
if path == "issues/7/comments?per_page=100":
assert args == ("--paginate", "--slurp")
comments = list(self.comments.values())
Expand Down Expand Up @@ -179,8 +182,11 @@ def invoke(name, event=None, run_id="101"):
("/ai-review F001 fixed", "author", True, "Review request accepted"),
("/ai-review", "writer", True, "Review request accepted"),
("/ai-review", "reader", False, "Permission denied"),
("/ai-review", "pilot-triager", False, "Permission denied"),
("/ai-review-stop", "author", False, "Permission denied"),
("/ai-review-stop", "pilot-triager", False, "Permission denied"),
("/ai-review-waive all intentional", "author", False, "Permission denied"),
("/ai-review-waive all intentional", "pilot-triager", False, "Permission denied"),
("/ai-reviewer", "author", False, None),
],
)
Expand All @@ -197,13 +203,25 @@ def test_command_permissions(pr, phase, body, actor, allowed, feedback):
assert "[View Actions run](https://github.com/example/project/actions/runs/101)" in comment["body"]


def test_label_checks_the_reviewer_and_removes_it_when_denied(pr, phase):
assert phase("authorize", pr.label_event(actor="writer")) == {}
@pytest.mark.parametrize("actor", ["writer", "unlisted-triager"])
def test_label_checks_the_reviewer_and_removes_it_when_denied(pr, phase, actor):
assert phase("authorize", pr.label_event(actor=actor)) == {}
[notice] = pr.comments.values()
assert "@writer" in notice["body"] and "RFC #21451" in notice["body"]
assert f"@{actor}" in notice["body"] and "RFC #21451" in notice["body"]
assert not pr.labels


def test_triage_label_removal_stops_the_session(pr, phase, history):
pr.seed(status="passed", round=1, total=1)
pr.labels = {"ai-review-passed"} # GitHub already removed ai-review.
stop = pr.label_event("unlabeled", actor="unlisted-triager")
assert phase("authorize", stop) == {"authorized": "true"}
assert not pr.labels
assert phase("prepare", stop) == {}
assert pr.state()["status"] == "stopped" and pr.state()["total"] == 1
assert pr.statuses == [(history.head, "error")]


def test_bot_command_is_ignored_even_with_write_access(pr, phase):
event = pr.command("/ai-review-stop", actor="writer", kind="Bot")
assert phase("authorize", event) == {}
Expand Down Expand Up @@ -232,16 +250,17 @@ def test_request_rechecks_live_pr_after_queue(pr, phase, agent, change, notice):


def test_label_then_manual_review_of_all_changes(pr, phase, agent, history):
start = pr.label_event()
start = pr.label_event(actor="pilot-triager")
assert phase("authorize", start) == {"authorized": "true"}
assert phase("prepare", start) == {"review": "true", "base": history.common, "head": history.head}
assert not pr.statuses
agent.return_value = result(findings=[finding(), finding(line=2), finding(line=None, severity="NIT")])
phase("review")
[summary] = pr.summaries()
assert "DeepSeek Harness headless · POC pilot" in summary["body"]
assert [comment["line"] for comment in pr.inline.values()] == [1, 2]
assert pr.state()["status"] == "reviewing" and pr.state()["total"] == 1
assert pr.statuses[-1] == (history.head, "failure")
assert pr.statuses == [(history.head, "pending"), (history.head, "failure")]

reply = "/ai-review\nF001 fixed in the first commit.\nF002 fixed in the second."
command = pr.command(reply)
Expand Down Expand Up @@ -286,13 +305,14 @@ def test_no_pass_when_review_is_blocked(pr, phase, agent, monkeypatch, history,
assert "truncated" in pr.state()["message"] and len(agent.call_args.args[1]["diff"]) == 12


def test_stop_blocks_inflight_publication(pr, phase, agent):
def test_stop_blocks_inflight_publication(pr, phase, agent, history):
phase("prepare", pr.command())
stop = pr.command("/ai-review-stop", "maintainer")
assert phase("authorize", stop) == {"authorized": "true"}
assert not pr.labels
phase("review")
assert not pr.summaries()
assert pr.statuses == [(history.head, "pending"), (history.head, "error")]
assert phase("prepare", stop) == {}
assert pr.state()["status"] == "stopped" and pr.state()["total"] == 0
assert agent.call_count == 1
Expand Down Expand Up @@ -410,6 +430,7 @@ def test_new_commit_during_review_discards_the_result(pr, phase, agent, history,
1,
)
assert not state["findings"] and not pr.inline and "ai-review-passed" not in pr.labels
assert pr.statuses == [(history.head, "pending"), (history.head, "error")]


@pytest.mark.parametrize(
Expand All @@ -420,13 +441,14 @@ def test_new_commit_during_review_discards_the_result(pr, phase, agent, history,
(result(updates=[dict(id="F999", status="resolved", evidence="Fixed.")]), ValueError),
],
)
def test_unsuccessful_analysis_can_be_rerun_without_losing_a_round(pr, phase, agent, bad_result, error):
def test_unsuccessful_analysis_can_be_rerun_without_losing_a_round(pr, phase, agent, history, bad_result, error):
previous = pr.seed(round=2, total=3)["body"]
event = pr.command()
agent.side_effect = [bad_result, result()]
phase("prepare", event)
with pytest.raises(error):
phase("review")
assert pr.statuses == [(history.head, "pending"), (history.head, "error")]
assert pr.summaries()[0]["body"] == previous
phase("prepare", event)
phase("review")
Expand All @@ -437,13 +459,16 @@ def test_unsuccessful_analysis_can_be_rerun_without_losing_a_round(pr, phase, ag
@pytest.mark.parametrize("write,expected_total", [("summary", 3), ("status", 4)])
def test_only_a_saved_summary_spends_the_round(pr, phase, monkeypatch, write, expected_total):
summary = pr.seed(round=2, total=3)
target = f"issues/comments/{summary['id']}" if write == "summary" else "statuses/"
phase("prepare", pr.command())

def fail_write(endpoint, *args, **kwargs):
if target in endpoint:
def fail_write(endpoint, *args, payload=None, **kwargs):
if write == "summary" and endpoint.endswith(f"issues/comments/{summary['id']}"):
raise RuntimeError("write failed")
return pr.api(endpoint, *args, **kwargs)
if write == "status" and "/statuses/" in endpoint and payload["state"] == "success":
raise RuntimeError("write failed")
if "/statuses/" in endpoint and payload["state"] == "error":
raise subprocess.CalledProcessError(1, ["gh", "api", endpoint])
return pr.api(endpoint, *args, payload=payload, **kwargs)

monkeypatch.setattr(ai, "gh", fail_write)
with pytest.raises(RuntimeError, match="write failed"):
Expand All @@ -463,7 +488,8 @@ def push_after_summary(endpoint, *args, **kwargs):
monkeypatch.setattr(ai, "gh", push_after_summary)
phase("review")
assert pr.state()["total"] == 1 and pr.state()["head"] == history.head
assert "ai-review-passed" not in pr.labels and pr.statuses == [(history.head, "pending")]
assert "ai-review-passed" not in pr.labels
assert pr.statuses == [(history.head, "pending"), (history.head, "error")]


def test_restore_latest_bot_summary_across_comment_pages(pr, phase, agent, history):
Expand Down Expand Up @@ -531,6 +557,7 @@ def flaky_git(repo, command, *args):
with pytest.raises(subprocess.CalledProcessError) as caught:
phase("prepare", pr.command())
assert caught.value is error
assert not pr.statuses
assert len(calls) == attempts and len(set(calls)) == 1
assert [item.args for item in sleep.call_args_list] == [(ai.GIT_FETCH_RETRY_DELAY_SECONDS,)] * (attempts - 1)
assert not pr.summaries()
Expand Down
Loading