Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(pr-approval-agent): surface PR and comment reactions to LLM reviewer (#67262)

Julian Bezb3332e0b324d
diff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.md
index 5b7ee817e6bb..c3788aa20438 100644
--- a/tools/pr-approval-agent/README.md
+++ b/tools/pr-approval-agent/README.md
@@ -67,6 +67,17 @@ LLM Review
- Claude Agent SDK with Read/Grep/Glob tools
- Explores the repo via git diff, reads source files if needed
- Looks for showstoppers: production breakage, security, missed deps
+ - Reads other reviewers' signals as context (not a gate): top-level review
+ states (annotated current-head vs older-commit), inline comments (tagged
+ resolved/outdated), and reactions (👍/👎/👀) on the PR and comments —
+ filtered to org members and an allowlist of reviewer bots (installed
+ apps like inkeep react for non-review reasons), never the PR author
+ - An 👀 reaction signals an in-flight review — the LLM refuses rather than
+ approving over someone who is mid-review
+ - For non-trivial changes, expects at least one independent reviewer (an
+ agent reviewer like Codex/Greptile/Claude, or a teammate) to have passed
+ over the current head; escalates otherwise. Trivial changes (docs, tests,
+ config/lockfile, typo/comment fixes) don't need one
- Gates are authoritative — LLM can tighten but never loosen
│
▼
diff --git a/tools/pr-approval-agent/github.py b/tools/pr-approval-agent/github.py
index 257d508be1b5..118778572b68 100644
--- a/tools/pr-approval-agent/github.py
+++ b/tools/pr-approval-agent/github.py
@@ -7,7 +7,8 @@ Also handles team membership checks for the ownership gate.
import json
import subprocess
-from dataclasses import dataclass
+from collections.abc import Callable
+from dataclasses import dataclass, field
from pathlib import Path
@@ -30,6 +31,7 @@ class PRData:
review_comments: list[dict]
check_runs: list[dict]
author_is_bot: bool = False
+ pr_reactions: list[dict] = field(default_factory=list)
@property
def file_paths(self) -> list[str]:
@@ -58,6 +60,18 @@ _TRUSTED_ASSOCIATIONS = {"MEMBER", "OWNER", "COLLABORATOR"}
# treated as bots. GitHub Apps already report type "Bot" and aren't listed here.
_BOT_MACHINE_USERS = {"posthog-bot"}
+# Bots whose reactions are deliberate review verdicts (👍 = reviewed clean,
+# 👀 = review in flight). Other installed apps react for unrelated reasons
+# (e.g. inkeep's 👎 is docs feedback), so bot reactions are allowlisted rather
+# than trusted wholesale. GraphQL returns bot logins with the "[bot]" suffix.
+_TRUSTED_REACTOR_BOTS = {
+ "chatgpt-codex-connector[bot]",
+ "copilot-pull-request-reviewer[bot]",
+ "greptile-apps[bot]",
+ "hex-security-app[bot]",
+ "veria-ai[bot]",
+}
+
def is_bot_author(user: dict) -> bool:
"""True when the PR author is a bot or machine account.
@@ -103,6 +117,87 @@ def _normalize_reviews_for_prompt(reviews_raw: list[dict], head_sha: str) -> lis
return normalized_reviews
+# GitHub spells reaction contents two ways: REST returns "+1"/"-1", GraphQL
+# returns "THUMBS_UP"/"THUMBS_DOWN". Normalize both to an emoji so the reviewer
+# sees a consistent signal regardless of which API surfaced the reaction.
+_REACTION_EMOJI = {
+ "+1": "👍",
+ "thumbs_up": "👍",
+ "-1": "👎",
+ "thumbs_down": "👎",
+ "laugh": "😄",
+ "hooray": "🎉",
+ "confused": "😕",
+ "heart": "❤️",
+ "rocket": "🚀",
+ "eyes": "👀",
+}
+
+
+def _reaction_emoji(content: str) -> str:
+ """Map a GitHub reaction content string (REST or GraphQL) to an emoji.
+
+ Unknown values pass through unchanged so a newly-added reaction type still
+ surfaces rather than silently disappearing.
+ """
+ return _REACTION_EMOJI.get(content.lower(), content)
+
+
+def _is_org_member(org: str, login: str) -> bool:
+ """Best-effort org-membership check; False on any error (fail closed)."""
+ try:
+ result = subprocess.run(
+ ["gh", "api", f"orgs/{org}/members/{login}"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ return result.returncode == 0
+ except subprocess.TimeoutExpired:
+ return False
+
+
+def _trusted_reactor_predicate(repo: str, author: str) -> Callable[[str], bool]:
+ """Build a memoized `login -> bool` gate for whose reactions to trust.
+
+ Reactions on a public PR can come from anyone, so only trust allowlisted
+ reviewer bots and org members, and never the PR author (a self-reaction is
+ not an independent signal). Unknown or erroring logins fail closed. Without
+ this, any GitHub user could block auto-approval with an 👀 or fake an
+ independent review with a 👍.
+ """
+ org = repo.split("/", 1)[0]
+ cache: dict[str, bool] = {}
+
+ def is_trusted(login: str) -> bool:
+ if not login or login == "ghost" or login == author:
+ return False
+ if login not in cache:
+ low = login.lower()
+ if low.endswith("[bot]"):
+ cache[login] = low in _TRUSTED_REACTOR_BOTS
+ else:
+ cache[login] = _is_org_member(org, login)
+ return cache[login]
+
+ return is_trusted
+
+
+def _normalize_reactions(node: dict, is_trusted: Callable[[str], bool]) -> list[dict]:
+ """Normalize a GraphQL Reactable node's trusted reactions to [{user, emoji}].
+
+ Works for any object that carries a `reactions` connection — the PR itself
+ or an individual review comment. Reactions from untrusted actors (see
+ `_trusted_reactor_predicate`) are dropped so they can't influence the verdict.
+ """
+ reactions = []
+ for rn in (node.get("reactions") or {}).get("nodes") or []:
+ login = (rn.get("user") or {}).get("login", "ghost")
+ if is_trusted(login):
+ reactions.append({"user": login, "emoji": _reaction_emoji(rn.get("content", ""))})
+ return reactions
+
+
def _gh_api(endpoint: str, *, paginate: bool = False) -> dict | list:
cmd = ["gh", "api", endpoint]
if paginate:
@@ -120,6 +215,12 @@ _REVIEW_THREADS_QUERY = """
query($owner: String!, $name: String!, $pr: Int!, $threadCursor: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $pr) {
+ reactions(first: 100) {
+ nodes {
+ content
+ user { login }
+ }
+ }
reviewThreads(first: 100, after: $threadCursor) {
pageInfo { hasNextPage endCursor }
nodes {
@@ -135,6 +236,12 @@ query($owner: String!, $name: String!, $pr: Int!, $threadCursor: String) {
body
databaseId
replyTo { databaseId }
+ reactions(first: 100) {
+ nodes {
+ content
+ user { login }
+ }
+ }
}
}
}
@@ -164,20 +271,27 @@ def _gh_graphql(query: str, variables: dict | None = None) -> dict:
return data
-def _fetch_review_threads(repo: str, pr_number: int) -> list[dict]:
- """Fetch review threads with resolution status via GraphQL.
+def _fetch_threads_and_reactions(repo: str, pr_number: int, author: str) -> tuple[list[dict], list[dict]]:
+ """Fetch review-thread comments and reactions on the PR in one GraphQL call.
- Returns a flat list of comment dicts enriched with is_resolved and
- is_outdated from their parent thread. Paginates through all threads
- and raises if any comment page is truncated.
+ Inline comments (each with their own reactions) and the reactions left on
+ the PR itself come back from the same query, so no extra REST round trip is
+ needed. Reactions are filtered to trusted, non-author actors. Returns
+ (comments, pr_reactions); raises if any comment page is truncated.
"""
owner, name = repo.split("/", 1)
variables: dict = {"owner": owner, "name": name, "pr": pr_number, "threadCursor": None}
+ is_trusted = _trusted_reactor_predicate(repo, author)
comments: list[dict] = []
+ pr_reactions: list[dict] = []
while True:
data = _gh_graphql(_REVIEW_THREADS_QUERY, variables)
- review_threads = data["data"]["repository"]["pullRequest"]["reviewThreads"]
+ pull_request = data["data"]["repository"]["pullRequest"]
+ # Reactions on the PR repeat on the pullRequest node on every page;
+ # re-reading the (≤20) nodes each pass is trivial and avoids a flag.
+ pr_reactions = _normalize_reactions(pull_request, is_trusted)
+ review_threads = pull_request["reviewThreads"]
threads = review_threads["nodes"]
for thread in threads:
@@ -202,6 +316,7 @@ def _fetch_review_threads(repo: str, pr_number: int) -> list[dict]:
"in_reply_to_id": reply_to["databaseId"] if reply_to else None,
"is_resolved": thread["isResolved"],
"is_outdated": thread["isOutdated"],
+ "reactions": _normalize_reactions(c, is_trusted),
}
)
@@ -210,7 +325,7 @@ def _fetch_review_threads(repo: str, pr_number: int) -> list[dict]:
break
variables["threadCursor"] = page_info["endCursor"]
- return comments
+ return comments, pr_reactions
def _git_diff_files(base_sha: str, head_sha: str, repo_root: Path) -> list[dict]:
@@ -281,7 +396,7 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData
ensure_commits(pr_number, head_sha, git_root)
files = _git_diff_files(base_sha, head_sha, git_root)
- review_comments = _fetch_review_threads(repo, pr_number)
+ review_comments, pr_reactions = _fetch_threads_and_reactions(repo, pr_number, pr["user"]["login"])
return PRData(
number=pr_number,
@@ -299,6 +414,7 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData
review_comments=review_comments,
check_runs=check_runs_resp.get("check_runs", []),
author_is_bot=is_bot_author(pr.get("user", {})),
+ pr_reactions=pr_reactions,
)
diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.py
index e03e52465848..f52a038cfdfc 100644
--- a/tools/pr-approval-agent/review_pr.py
+++ b/tools/pr-approval-agent/review_pr.py
@@ -504,6 +504,7 @@ class Pipeline:
"stamphog_commit_type": cl.get("commit_type") or "",
"stamphog_files_changed": len(pr.files),
"stamphog_lines_total": pr.lines_total,
+ "stamphog_pr_reactions_count": len(pr.pr_reactions),
"stamphog_gate_verdict": gate_verdict,
"stamphog_llm_verdict": llm_verdict,
"stamphog_final_verdict": self.final_verdict,
diff --git a/tools/pr-approval-agent/reviewer.py b/tools/pr-approval-agent/reviewer.py
index 7654387fcc4a..f50f12a4bb8c 100644
--- a/tools/pr-approval-agent/reviewer.py
+++ b/tools/pr-approval-agent/reviewer.py
@@ -33,7 +33,7 @@ try:
except ImportError:
_POSTHOG_AI_AVAILABLE = False
-MODEL = "claude-sonnet-4-6"
+MODEL = "claude-sonnet-5"
_CONTROL_CHARS_RE = re.compile(r"[^\x20-\x7E\n\t]")
@@ -44,6 +44,11 @@ def _sanitize_untrusted(text: str, max_len: int = 200) -> str:
return _CONTROL_CHARS_RE.sub("", text)[:max_len]
+def _reaction_token(reaction: dict) -> str:
+ """Render one reaction as `👍 @user`, with the user login sanitized."""
+ return f"{reaction['emoji']} @{_sanitize_untrusted(reaction['user'], max_len=50)}"
+
+
VERDICT_SCHEMA = {
"type": "json_schema",
"schema": {
@@ -140,28 +145,40 @@ REVIEWER_SYSTEM = textwrap.dedent(
- Fine: typo fixes, log strings, test fixes, comments, mechanical refactors
- ESCALATE: behavioral changes to business logic, API contracts, data models
- Review comments (inline feedback only, approval states are hidden):
- - Top-level reviews are annotated as either "current head" or "older commit".
- Treat reviews on the current head as active signals. Treat older-commit
- reviews as historical context only, and only flag them if the current diff
+ Reviews, comments, and reactions:
+ - Each top-level review shows its state (APPROVED / COMMENTED /
+ CHANGES_REQUESTED) and whether it landed on the current head or an older
+ commit. Treat current-head reviews as active signals; treat older-commit
+ reviews as historical context, acting on them only if the current diff
still shows the same unresolved issue.
- - Comments are tagged [resolved], [outdated], or unmarked (unresolved).
- Resolution status is a signal, not gospel — use your judgment.
- - Resolved/outdated comments are usually fine, but still skim them.
- If a resolved comment raised a serious concern (security, data
- loss) that the diff clearly did NOT address, flag it anyway.
- - For unresolved comments: check whether a subsequent commit or the
- current diff already addressed the concern. Authors often fix
- issues in follow-up commits without explicitly resolving the
- thread. Only flag comments that remain genuinely unaddressed in
- the current code.
- - Substantive comments that remain unaddressed → REFUSE
- - "Zero reviews" means no top-level reviews and no inline comments.
- Zero reviews is fine for low-risk changes (trivial fixes, typos,
- test updates, config tweaks). For anything higher-risk, treat zero
- reviews as a concern and ESCALATE unless there's a strong,
- specific justification to APPROVE.
- - Bot comments with valid concerns that were ignored → ESCALATE
+ - Inline comments are tagged [resolved], [outdated], or unmarked
+ (unresolved). Resolution status is a signal, not gospel — use judgment. A
+ resolved or outdated comment that raised a serious concern (security, data
+ loss) the diff clearly did NOT address → flag it anyway. For unresolved
+ comments, check whether a later commit already addressed the concern
+ before flagging; substantive ones still unaddressed → REFUSE.
+ - Reactions (👍, 👎, 👀, etc.) on the PR and on individual review comments
+ are provided — already filtered to trusted org members and bot reviewers,
+ never the PR author. A 👍 from an agent reviewer or teammate is how a bot
+ often signals "no concerns" — a mild positive; a 👎 or 😕 is a mild
+ negative. These two are weak evidence: never approve on a 👍 alone or
+ refuse on a 👎 alone — corroborate against the diff.
+ - An 👀 (eyes) reaction means a review is in flight — someone is actively
+ looking at the PR right now. Do NOT approve over an in-progress review:
+ REFUSE and tell the author to wait for that reviewer to finish and
+ re-request. This overrides any 👍 present.
+ - Bot/agent comments with valid concerns that were ignored → ESCALATE.
+
+ Independent review (you are not a substitute for one):
+ - Stamphog is the only automated approver in this path, so for any
+ non-trivial change require at least one independent reviewer — an agent
+ reviewer (Codex, Greptile, Claude) or a human teammate — to have passed
+ over the current head: an APPROVED or COMMENTED review with no unresolved
+ concerns, or a 👍 on the PR or a review comment. If none has, ESCALATE and
+ tell the author to get a review before re-requesting.
+ - Trivial class where no independent review is needed: docs-only, test-only,
+ config/lockfile tweaks, and typo/comment/log-string fixes — purely
+ cosmetic or low-risk additive changes. Judge from the tier and diff.
Tools: You have Read, Grep, and Glob (restricted to the repo directory).
All PR metadata (comments, ownership) is in the prompt — do NOT fetch
@@ -270,6 +287,7 @@ class Reviewer:
"stamphog_reviewers": reviewers,
"stamphog_reviews_count": len(pr.reviews),
"stamphog_inline_comments_count": len(pr.review_comments),
+ "stamphog_pr_reactions_count": len(pr.pr_reactions),
"stamphog_tier": classification.get("tier", ""),
"stamphog_t1_subclass": classification.get("t1_subclass", ""),
"stamphog_breadth": classification.get("breadth", ""),
@@ -370,9 +388,12 @@ class Reviewer:
elif c.get("is_outdated"):
status = " [outdated]"
safe_path = _sanitize_untrusted(c["path"], max_len=200)
- lines.append(f" - @{safe_user}{reply}{status} on {safe_path}: {safe_body}")
+ reactions = self._format_reactions(c.get("reactions"))
+ lines.append(f" - @{safe_user}{reply}{status} on {safe_path}: {safe_body}{reactions}")
review_comments = "\n".join(lines)
+ pr_reactions = "\n".join(f" - {_reaction_token(r)}" for r in pr.pr_reactions)
+
ownership = self._format_ownership(cl)
gate_lines = []
@@ -400,7 +421,7 @@ class Reviewer:
Size: {pr.lines_total} lines ({pr.lines_added}+/{pr.lines_deleted}-), {len(pr.files)} files
Scope: {cl["breadth"]}
Commit type: {cl.get("commit_type") or "unknown"}
- Reviews: {len(pr.reviews)} top-level, {len(pr.review_comments)} inline
+ Reviews: {len(pr.reviews)} top-level, {len(pr.review_comments)} inline, {len(pr.pr_reactions)} PR reactions
{ownership}
@@ -424,9 +445,18 @@ class Reviewer:
Inline comments:
{review_comments}
+
+ Reactions on the PR:
+ {pr_reactions}
--- END UNTRUSTED CONTENT ---
""")
+ def _format_reactions(self, reactions: list[dict] | None) -> str:
+ """Render a compact reaction annotation like ` {👍 @greptile-apps}`."""
+ if not reactions:
+ return ""
+ return " {" + ", ".join(_reaction_token(r) for r in reactions) + "}"
+
def _format_ownership(self, cl: dict) -> str:
ownership = cl.get("ownership", {})
teams = ownership.get("teams", [])
diff --git a/tools/pr-approval-agent/test_github.py b/tools/pr-approval-agent/test_github.py
index 10dafbed805c..7b464cffd068 100644
--- a/tools/pr-approval-agent/test_github.py
+++ b/tools/pr-approval-agent/test_github.py
@@ -2,7 +2,8 @@
import pytest
-from github import _normalize_reviews_for_prompt, is_bot_author
+import github
+from github import _normalize_reviews_for_prompt, _reaction_emoji, _trusted_reactor_predicate, is_bot_author
def test_normalize_reviews_marks_current_head_and_preserves_stale_reviews() -> None:
@@ -77,6 +78,40 @@ def test_normalize_reviews_filters_by_trust_source(
assert len(normalized) == expected_count
+ "content,expected",
+ [
+ pytest.param("+1", "👍", id="rest-thumbs-up"),
+ pytest.param("THUMBS_UP", "👍", id="graphql-thumbs-up"),
+ pytest.param("-1", "👎", id="rest-thumbs-down"),
+ pytest.param("EYES", "👀", id="graphql-eyes"),
+ pytest.param("sparkle", "sparkle", id="unknown-passthrough"),
+ ],
+)
+def test_reaction_emoji_normalizes_rest_and_graphql(content: str, expected: str) -> None:
+ assert _reaction_emoji(content) == expected
+
+
+ "login,expected",
+ [
+ pytest.param("prauthor", False, id="author-self-reaction"),
+ pytest.param("ghost", False, id="deleted-user"),
+ pytest.param("", False, id="empty-login"),
+ pytest.param("greptile-apps[bot]", True, id="allowlisted-bot"),
+ pytest.param("inkeep[bot]", False, id="unlisted-bot"),
+ pytest.param("teammate", True, id="org-member"),
+ pytest.param("outsider", False, id="external-non-member"),
+ ],
+)
+def test_trusted_reactor_predicate_gates_untrusted_and_author(
+ monkeypatch: pytest.MonkeyPatch, login: str, expected: bool
+) -> None:
+ monkeypatch.setattr(github, "_is_org_member", lambda org, member: member == "teammate")
+ is_trusted = _trusted_reactor_predicate("PostHog/posthog", author="prauthor")
+ assert is_trusted(login) is expected
+
+
@pytest.mark.parametrize(
"user,expected",
[