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(stamphog): reduce denials that humans approve unchanged (#68045)

Paul D'Ambra01bfd7108786
diff --git a/.github/workflows/pr-approval-agent.yml b/.github/workflows/pr-approval-agent.yml
index d3c246c4cdc1..a52f16ade8ae 100644
--- a/.github/workflows/pr-approval-agent.yml
+++ b/.github/workflows/pr-approval-agent.yml
@@ -35,7 +35,11 @@ jobs:
|| needs.decide-delta.result == 'failure'
)
runs-on: ubuntu-latest
- timeout-minutes: 10
+ # Budget for the in-flight-bot-review wait (5 min of sleeps plus the
+ # per-poll refetches, so wall-clock exceeds it) plus the LLM review —
+ # see BOT_REVIEW_WAIT_BUDGET_SECONDS in review_pr.py. The cap costs
+ # nothing unless a run hangs; runners bill actual minutes.
+ timeout-minutes: 20
steps:
- name: Get app token
@@ -119,14 +123,17 @@ jobs:
--repo "$REPO"
fi
- # A substantive non-APPROVED verdict (REFUSE/ESCALATE)
- # removes the label, breaking the auto-rerun loop until a
- # human re-applies it after addressing the feedback. ERROR
- # means the review agent couldn't reach its LLM backend
- # (auth/credit/outage) — that's not a verdict on the PR, so
- # keep the label and let it retry rather than silently
- # dropping it across every queued PR during an outage.
- if [ "$VERDICT" != "APPROVED" ] && [ "$VERDICT" != "ERROR" ]; then
+ # Only the two substantive verdicts strip the label — a
+ # REFUSE/ESCALATE means the author must address feedback and
+ # re-apply. Everything else fails toward retention: ERROR
+ # (LLM backend down), WAIT (reviewer bot mid-review), and an
+ # empty verdict (script crash / job cancelled before
+ # review.json was written) are not verdicts on the PR, and
+ # retention just means the next push retries. An explicit
+ # strip-list also means future verdicts keep the label by
+ # default instead of everyone remembering to extend a
+ # keep-list.
+ if [ "$VERDICT" = "REFUSED" ] || [ "$VERDICT" = "ESCALATE" ]; then
gh pr edit "$PR" --remove-label stamphog \
--repo "$REPO"
fi
diff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.md
index ff566a39cec3..b1e616fb300b 100644
--- a/tools/pr-approval-agent/README.md
+++ b/tools/pr-approval-agent/README.md
@@ -8,12 +8,17 @@ Deterministic safety gates first, then Claude reviews for showstoppers.
Add the `stamphog` label to a non-draft PR.
The GitHub Action runs the agent and posts an approval or comment.
On approval the label stays so it's visible which PRs were stamphog'd.
-On a substantive non-approval (`REFUSE`/`ESCALATE`) the label is removed so it
-can be re-applied once the feedback is addressed.
+Only a substantive non-approval (`REFUSE`/`ESCALATE`) removes the label, so it
+can be re-applied once the feedback is addressed; every other outcome —
+including a crashed run that produced no verdict — keeps the label and retries
+on the next push.
If the review agent can't reach its LLM backend (credentials, credit, or
outage) it returns `ERROR` and **keeps** the label — a transient infra failure
must not silently drop labels across every queued PR. The review retries on the
-next push, or re-apply the label once the backend recovers. When the whole
+next push, or re-apply the label once the backend recovers.
+`WAIT` also keeps the label: it means an allowlisted reviewer bot still had a
+review in flight (👀 reaction) after the polling budget — not a verdict on the
+PR, so the next push retries automatically. When the whole
fleet of stamphog reviews suddenly returns `ERROR`, suspect the
`STAMPHOG_ANTHROPIC_API_KEY` org secret first (stamphog uses its own dedicated
Anthropic key, separate from the shared `ANTHROPIC_API_KEY`).
@@ -54,7 +59,15 @@ Deny-list (hard gate)
│
▼
Size ceiling (hard gate)
- - >500 lines or >20 files → too large for auto-review
+ - >500 substantive lines or >20 substantive files → too large for auto-review
+ - Docs (.md/.txt/.rst anywhere; artifact-extension files under docs/),
+ snapshots (.snap/.ambr, __snapshots__/), images,
+ `.lock`-extension files (e.g. `yarn.lock`), and generated/ artifacts
+ (regenerated-artifact extensions only: .ts/.tsx/.js/.jsx/.json/.md/.snap/.pyi/.txt)
+ don't count toward the ceiling — they inflate diffs without adding review
+ surface. Note: `pnpm-lock.yaml` and `package-lock.json` are not `.lock`-extension
+ files and do count toward the ceiling. All files still count toward tier
+ classification and still appear in the diff the LLM reads.
│
▼
Tier classification
@@ -63,6 +76,21 @@ Tier classification
- T2-never: caught by deny-list
│
▼
+Wait for in-flight bot reviews (skipped when gates already denied)
+ - Reviewer bots (greptile, hex-security, codex) put 👀 on the PR while
+ reviewing and swap it for a verdict reaction minutes later; stamphog is
+ triggered at the same moment, so an 👀 at fetch time is a race, not a
+ lasting state
+ - Polls until allowlisted-bot 👀 reactions clear (up to 5 min); if one
+ remains, verdict is WAIT — label kept, next push retries
+ - Bot 👀 older than ~45 min is a crashed reviewer, not an in-flight one —
+ ignored, so a wedged bot can't stall every review (reactions never
+ expire and humans can't remove another app's reaction)
+ - Human 👀 reactions are not waited on — the LLM refuses over them instead
+ - If the wait refetched the PR, classification and gates re-run on the
+ fresh data before the LLM sees it
+ │
+ ▼
LLM Review
- Claude Agent SDK with Read/Grep/Glob tools
- Explores the repo via git diff, reads source files if needed
@@ -73,14 +101,19 @@ LLM Review
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
+ approving over someone who is mid-review (bot 👀 races are waited out
+ before the LLM runs; see above)
- Stamphog's own prior reviews (stamphog[bot] refusals, github-actions[bot]
- approvals) are excluded from the prompt — they describe an earlier snapshot
- of the PR and are never independent review signal
+ approvals) and its own inline comments are excluded from the prompt — they
+ describe an earlier snapshot of the PR and are never independent review
+ signal. Quoted stamphog verdicts in other reviewers' comments are treated
+ as history, not tampering
- 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
+ over the current head; escalates otherwise. No independent review needed
+ for trivial changes (docs, tests, config/lockfile, typo/comment fixes) or
+ for small single-area changes (T1a/T1b) with tests by owning-team authors
+ with no outstanding reviewer concerns — humans approve those unchanged
- Gates are authoritative — LLM can tighten but never loosen
│
▼
@@ -131,7 +164,9 @@ If the check hasn't completed yet when stamphog runs, stamphog refuses with a me
### Ownership
Uses `.github/CODEOWNERS-soft` as context for the LLM (not a hard gate).
-Cross-team typo/test/comment fixes are fine; behavioral changes to business logic get escalated.
+Cross-team typo/test/comment fixes are fine, as are small well-tested behavioral
+fixes (T1a/T1b) with no outstanding reviewer concerns; API contract, data model,
+and larger behavioral changes get escalated.
## Evidence bundle
diff --git a/tools/pr-approval-agent/gates.py b/tools/pr-approval-agent/gates.py
index fe1cce87c5fe..aca706b92762 100644
--- a/tools/pr-approval-agent/gates.py
+++ b/tools/pr-approval-agent/gates.py
@@ -546,12 +546,63 @@ def detect_ownership(files: list[str], rules: list[CodeownersRule]) -> dict:
}
-# ── Tier assignment ──────────────────────────────────────────────
+# ── Size gate ────────────────────────────────────────────────────
MAX_LINES = 500
MAX_FILES = 20
+# Files that inflate a diff without adding review surface: prose docs,
+# regenerated artifacts, and test snapshots. The size ceiling counts only the
+# substantive remainder, so a 2000-line docs rewrite or type regen isn't
+# auto-denied. Exempt files still count toward tier/subclass classification
+# (which calibrates LLM scrutiny) and still appear in the diff the LLM reads.
+# Deliberately narrower than ALLOW_ONLY_EXTENSIONS: .json/.yaml/.toml configs
+# change runtime behavior, so they stay in the count.
+SIZE_EXEMPT_EXTENSIONS = {
+ ".md",
+ ".mdx",
+ ".txt",
+ ".rst",
+ ".snap",
+ ".ambr",
+ ".storyshot",
+ ".svg",
+ ".png",
+ ".jpg",
+ ".jpeg",
+ ".gif",
+ ".ico",
+ ".webp",
+ ".lock",
+}
+
+# __snapshots__/ deliberately has no directory-wide exemption: snapshot
+# artifacts are covered by extension (.snap/.ambr/.storyshot), so an
+# executable file placed under a snapshots dir still counts toward the
+# ceiling — same reasoning as the extension allowlists below.
+_SIZE_EXEMPT_PATH_RE = re.compile(
+ r"(?:^|/)docs/.*\.(ts|tsx|js|jsx|json|md|snap|pyi|txt)$"
+ r"|(?:^|/)generated/.*\.(ts|tsx|js|jsx|json|md|snap|pyi|txt)$"
+ r"|\.gen\.(ts|tsx|js|jsx)$"
+ r"|\.generated\.(ts|tsx|js|jsx)$"
+ r"|^frontend/src/queries/schema/",
+ re.IGNORECASE,
+)
+
+
+def is_size_exempt(path: str) -> bool:
+ return Path(path).suffix.lower() in SIZE_EXEMPT_EXTENSIONS or bool(_SIZE_EXEMPT_PATH_RE.search(path))
+
+
+def substantive_size(files: list[dict]) -> tuple[int, int]:
+ """(changed lines, file count) over the files that count toward the size ceiling."""
+ counted = [f for f in files if not is_size_exempt(f["filename"])]
+ return sum(f["additions"] + f["deletions"] for f in counted), len(counted)
+
+
+# ── Tier assignment ──────────────────────────────────────────────
+
def assign_tier(
*,
diff --git a/tools/pr-approval-agent/github.py b/tools/pr-approval-agent/github.py
index 145652d79c3e..0d6559d2c380 100644
--- a/tools/pr-approval-agent/github.py
+++ b/tools/pr-approval-agent/github.py
@@ -64,7 +64,7 @@ _BOT_MACHINE_USERS = {"posthog-bot"}
# 👀 = 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 = {
+TRUSTED_REACTOR_BOTS = {
"chatgpt-codex-connector[bot]",
"copilot-pull-request-reviewer[bot]",
"greptile-apps[bot]",
@@ -188,7 +188,7 @@ def _trusted_reactor_predicate(repo: str, author: str) -> Callable[[str], bool]:
if login not in cache:
low = login.lower()
if low.endswith("[bot]"):
- cache[login] = low in _TRUSTED_REACTOR_BOTS
+ cache[login] = low in TRUSTED_REACTOR_BOTS
else:
cache[login] = _is_org_member(org, login)
return cache[login]
@@ -207,7 +207,13 @@ def _normalize_reactions(node: dict, is_trusted: Callable[[str], bool]) -> list[
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", ""))})
+ reactions.append(
+ {
+ "user": login,
+ "emoji": _reaction_emoji(rn.get("content", "")),
+ "created_at": rn.get("createdAt"),
+ }
+ )
return reactions
@@ -233,6 +239,7 @@ query($owner: String!, $name: String!, $pr: Int!, $threadCursor: String) {
reactions(first: 100) {
nodes {
content
+ createdAt
user { login }
}
}
@@ -254,6 +261,7 @@ query($owner: String!, $name: String!, $pr: Int!, $threadCursor: String) {
reactions(first: 20) {
nodes {
content
+ createdAt
user { login }
}
}
@@ -317,6 +325,13 @@ def _fetch_threads_and_reactions(repo: str, pr_number: int, author: str) -> tupl
f"has >50 comments — pagination not implemented, escalate to human review"
)
for c in comment_page["nodes"]:
+ # Same exclusion as _normalize_reviews_for_prompt: stamphog's
+ # own inline comments describe an earlier snapshot, and feeding
+ # them back makes the next run read them as impersonation.
+ # Reactions on these comments are also dropped — a 👍 on
+ # stamphog's comment endorses stamphog's verdict, not the PR.
+ if (c.get("author") or {}).get("login") in _SELF_REVIEW_LOGINS:
+ continue
assoc = c.get("authorAssociation", "")
is_bot = (c.get("author") or {}).get("__typename") == "Bot"
if assoc not in _TRUSTED_ASSOCIATIONS and assoc != "BOT" and not is_bot:
diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.py
index f52a038cfdfc..3026ee917757 100644
--- a/tools/pr-approval-agent/review_pr.py
+++ b/tools/pr-approval-agent/review_pr.py
@@ -24,6 +24,7 @@ import json
import time
import argparse
from dataclasses import dataclass, field
+from datetime import UTC, datetime
from pathlib import Path
from gates import (
@@ -39,10 +40,11 @@ from gates import (
parse_codeowners_soft,
parse_conventional_commit,
scope_breadth,
+ substantive_size,
t1_risk_subclass,
test_only,
)
-from github import PRData, check_team_membership, fetch_pr
+from github import TRUSTED_REACTOR_BOTS, PRData, check_team_membership, fetch_pr
from migration_risk import migration_check_pending, safe_migration_files
from reviewer import Reviewer
@@ -111,6 +113,33 @@ def _is_retryable_error(err_msg: str) -> bool:
return not any(pattern in err_msg for pattern in _NON_RETRYABLE_PATTERNS)
+# Reviewer bots put 👀 on a PR while reviewing and swap it for a verdict
+# reaction within minutes. Stamphog is usually triggered at the same moment
+# (label applied at PR open), so an 👀 at fetch time is almost always a race
+# with a bot mid-review, not a lasting state — poll until it clears instead
+# of refusing. Budget must leave room for the LLM review inside the
+# workflow job timeout.
+BOT_REVIEW_WAIT_BUDGET_SECONDS = 300
+BOT_REVIEW_POLL_SECONDS = 30
+
+# A bot 👀 much older than any real review is a crashed reviewer, not an
+# in-flight one — reactions never expire and a human can't remove another
+# app's reaction, so without this cutoff a wedged bot would make every run
+# WAIT forever. Reactions missing a timestamp count as fresh (fail toward
+# waiting).
+BOT_EYES_MAX_AGE_SECONDS = 45 * 60
+
+
+def _reaction_age_seconds(created_at: str | None) -> float:
+ if not created_at:
+ return 0.0
+ try:
+ created = datetime.fromisoformat(created_at)
+ except ValueError:
+ return 0.0
+ return (datetime.now(UTC) - created).total_seconds()
+
+
# ── Gate result ──────────────────────────────────────────────────
@@ -133,6 +162,7 @@ class Pipeline:
self.repo = repo
self.dry_run = dry_run
self.verbose = verbose
+ self._wait_refetched_pr = False
self.pr: PRData | None = None
self.classification: dict = {}
self.gate_results: list[GateResult] = []
@@ -146,21 +176,37 @@ class Pipeline:
if self.pr.author_is_bot:
return self._refuse_bot_author()
- self._classify()
- self._run_gates()
+ gate_verdict = self._classify_and_gate()
if self._only_pending_migration_check():
return self._refuse_pending_migration_check()
- gate_verdict = self._gate_verdict()
-
if self.dry_run:
self.final_verdict = "DRY-RUN"
return self.final_verdict
+ # Gate denials skip the wait: a refusal can't approve over an
+ # in-flight review, so waiting would only burn runner minutes before
+ # the inevitable REFUSE. The wait refetches the PR, so on the paths
+ # that did wait, re-derive classification and gates from fresh data.
+ if gate_verdict != "DENIED":
+ wait_verdict = self._handle_in_flight_bot_reviews()
+ if wait_verdict:
+ return wait_verdict
+ if self._wait_refetched_pr:
+ gate_verdict = self._classify_and_gate()
+ if self._only_pending_migration_check():
+ return self._refuse_pending_migration_check()
+
self._llm_review(gate_verdict)
return self.final_verdict
+ def _classify_and_gate(self) -> str:
+ self.gate_results = []
+ self._classify()
+ self._run_gates()
+ return self._gate_verdict()
+
def _only_pending_migration_check(self) -> bool:
"""True when the only thing blocking approval is a pending Migration risk check.
@@ -197,6 +243,62 @@ class Pipeline:
self._capture_review_completed("DENIED", "BOT-AUTHOR")
return self.final_verdict
+ def _in_flight_bot_reviewers(self) -> list[str]:
+ """Allowlisted reviewer bots with a fresh 👀 reaction on the PR."""
+ return sorted(
+ {
+ r["user"]
+ for r in self.pr.pr_reactions
+ if r["emoji"] == "👀"
+ and r["user"].lower() in TRUSTED_REACTOR_BOTS
+ and _reaction_age_seconds(r.get("created_at")) <= BOT_EYES_MAX_AGE_SECONDS
+ }
+ )
+
+ def _handle_in_flight_bot_reviews(self) -> str | None:
+ """Wait out the reviewer-bot 👀 race; WAIT if a bot is still reviewing.
+
+ Returns None when no bot review is (or remains) in flight. Human 👀
+ reactions are not waited on — humans take longer than any polling
+ budget, and the LLM refuses over them with a clear message instead.
+ The WAIT verdict keeps the stamphog label (like ERROR) so the review
+ retries on the next push rather than demanding a human re-label.
+ """
+ bots = self._in_flight_bot_reviewers()
+ if not bots:
+ return None
+
+ deadline = time.monotonic() + BOT_REVIEW_WAIT_BUDGET_SECONDS
+ while time.monotonic() < deadline:
+ print(_warn(f"in-flight bot review ({', '.join(bots)}) — waiting {BOT_REVIEW_POLL_SECONDS}s"))
+ time.sleep(BOT_REVIEW_POLL_SECONDS)
+ try:
+ self._fetch()
+ except Exception as exc:
+ print(_warn(f"refetch failed ({exc}); treating as still in flight"))
+ continue
+ self._wait_refetched_pr = True
+ bots = self._in_flight_bot_reviewers()
+ if not bots:
+ return None
+
+ bot_list = ", ".join(f"@{b}" for b in bots)
+ self.final_verdict = "WAIT"
+ self.reviewer_output = {
+ "verdict": "WAIT",
+ "reasoning": (
+ f"{bot_list} still {'have' if len(bots) > 1 else 'has'} a review in flight (👀) after "
+ f"{BOT_REVIEW_WAIT_BUDGET_SECONDS // 60} minutes — not approving over an "
+ "unfinished review. The `stamphog` label has been kept; the review re-runs "
+ "on the next push, or remove and re-apply the label once the reviewer finishes."
+ ),
+ "risk": "unknown",
+ "issues": [],
+ }
+ print(f"\n{_warn('WAIT')} — bot review still in flight ({bot_list}); label retained for retry")
+ self._capture_review_completed("SKIPPED", "WAIT")
+ return self.final_verdict
+
def _refuse_pending_migration_check(self) -> str:
self.final_verdict = "REFUSED"
self.reviewer_output = {
@@ -359,16 +461,22 @@ class Pipeline:
return self.classification["ownership_summary"]
def _check_size(self) -> tuple[bool, str]:
- lines = self.pr.lines_total
- files = len(self.pr.files)
+ lines, files = substantive_size(self.pr.files)
binary_count = sum(1 for f in self.pr.files if f.get("binary"))
- suffix = f", {binary_count} binary" if binary_count else ""
+ exempt_files = len(self.pr.files) - files
+ suffix_parts = []
+ if binary_count:
+ suffix_parts.append(f"{binary_count} binary")
+ if exempt_files:
+ suffix_parts.append(f"{self.pr.lines_total}L/{len(self.pr.files)}F incl. docs/generated/snapshots")
+ suffix = (", " + "; ".join(suffix_parts)) if suffix_parts else ""
if lines > MAX_LINES or files > MAX_FILES:
return (
False,
- f"too large for auto-review ({lines}L, {files}F{suffix} — ceiling is {MAX_LINES}L / {MAX_FILES}F)",
+ f"too large for auto-review ({lines}L, {files}F substantive{suffix} — "
+ f"ceiling is {MAX_LINES}L / {MAX_FILES}F)",
)
- return True, f"{lines}L, {files}F{suffix} within ceiling"
+ return True, f"{lines}L, {files}F substantive{suffix} — within ceiling"
def _check_tier(self) -> tuple[bool, str]:
cl = self.classification
diff --git a/tools/pr-approval-agent/reviewer.py b/tools/pr-approval-agent/reviewer.py
index a2dc17f2ff1b..03d57db735a5 100644
--- a/tools/pr-approval-agent/reviewer.py
+++ b/tools/pr-approval-agent/reviewer.py
@@ -158,7 +158,11 @@ REVIEWER_SYSTEM = textwrap.dedent(
- Author on owning team: not a concern
- Author NOT on owning team:
- Fine: typo fixes, log strings, test fixes, comments, mechanical refactors
- - ESCALATE: behavioral changes to business logic, API contracts, data models
+ - Fine: small behavioral fixes (T1a/T1b) with test coverage and no
+ outstanding reviewer concerns — independent review still required
+ (the no-review carve-out below applies to owning-team authors only)
+ - ESCALATE: changes to API contracts or data models, and larger (T1c+)
+ behavioral changes to business logic
Reviews, comments, and reactions:
- Each top-level review shows its state (APPROVED / COMMENTED /
@@ -181,12 +185,15 @@ REVIEWER_SYSTEM = textwrap.dedent(
- 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.
+ re-request. This overrides any 👍 present. (Reviewer bots clear their 👀
+ within minutes and the pipeline waits those out before invoking you, so
+ any 👀 you see — bot or human — is a genuine in-flight review.)
- Bot/agent comments with valid concerns that were ignored → ESCALATE.
- Your own prior reviews (posted as stamphog[bot] or github-actions[bot])
are excluded from this context — each run judges the PR's current state
- fresh. If another reviewer quotes an earlier stamphog verdict, treat it
- as history, not as an independent signal or as tampering.
+ fresh. If a review or inline comment quotes or restates an earlier
+ stamphog verdict, treat it as history — never as an independent signal,
+ as tampering, or as someone impersonating you.
Independent review (you are not a substitute for one):
- Stamphog is the only automated approver in this path, so for any
@@ -195,9 +202,12 @@ REVIEWER_SYSTEM = textwrap.dedent(
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.
+ - Classes where no independent review is needed (judge from tier and diff):
+ - docs-only, test-only, config/lockfile tweaks, and typo/comment/
+ log-string fixes — purely cosmetic or low-risk additive changes
+ - small single-area changes (T1a/T1b) with test coverage, authored by
+ someone on the owning team, with no reviewer concerns outstanding —
+ humans approve these unchanged, so escalating just adds a rubber stamp
Tools: You have Read, Grep, and Glob (restricted to the repo directory).
All PR metadata (comments, ownership) is in the prompt — do NOT fetch
diff --git a/tools/pr-approval-agent/test_gates.py b/tools/pr-approval-agent/test_gates.py
index 4280dd0231d0..66ba0d218548 100644
--- a/tools/pr-approval-agent/test_gates.py
+++ b/tools/pr-approval-agent/test_gates.py
@@ -2,7 +2,7 @@
import pytest
-from gates import detect_deny_categories
+from gates import detect_deny_categories, is_size_exempt, substantive_size
# ── False positives that should NOT trigger ──────────────────────
@@ -252,3 +252,52 @@ def test_dwh_source_still_denies_non_auth_categories() -> None:
def test_dwh_source_mixed_still_denies(files: list[str], subject: str) -> None:
# Auth gate must still fire when any non-source file is in the change set.
assert "auth" in detect_deny_categories(files, subject)
+
+
+# ── Size-ceiling exemptions ──────────────────────────────────────
+
+
+ "path, exempt",
+ [
+ pytest.param("docs/internal/monorepo-layout.md", True, id="markdown"),
+ pytest.param(".agents/skills/foo/SKILL.md", True, id="skill-markdown"),
+ pytest.param("docs/example-snippet.ts", True, id="docs-dir-artifact-extension"),
+ pytest.param("posthog/api/test/__snapshots__/test_api.ambr", True, id="ambr-snapshot"),
+ pytest.param("frontend/__snapshots__/scene.storyshot", True, id="storyshot-extension"),
+ pytest.param("posthog/test/__snapshots__/helper.py", False, id="executable-under-snapshots-counted"),
+ pytest.param("frontend/src/generated/core/api.schemas.ts", True, id="generated-dir"),
+ pytest.param("products/tasks/frontend/generated/api.ts", True, id="product-generated-dir"),
+ pytest.param("frontend/src/queries/schema/schema-general.ts", True, id="queries-schema"),
+ pytest.param("frontend/src/types.gen.ts", True, id="dot-gen-suffix"),
+ pytest.param("pnpm-lock.yaml", False, id="lockfile-yaml-counted"),
+ pytest.param("uv.lock", True, id="lockfile-lock-ext"),
+ pytest.param("posthog/api/insight.py", False, id="python-code"),
+ pytest.param("frontend/src/scenes/insights/Insight.tsx", False, id="frontend-code"),
+ pytest.param("posthog/settings/web.py", False, id="settings-code"),
+ pytest.param("docker-compose.dev.yml", False, id="yaml-config"),
+ pytest.param("package.json", False, id="json-config"),
+ pytest.param("regenerated_totals.py", False, id="generated-substring-not-dir"),
+ pytest.param("frontend/src/generated/core/evil.py", False, id="generated-dir-executable-py"),
+ pytest.param("frontend/src/generated/core/build.sh", False, id="generated-dir-executable-sh"),
+ pytest.param("docs/generate_sidebar.py", False, id="docs-dir-executable-py"),
+ ],
+)
+def test_is_size_exempt(path: str, exempt: bool) -> None:
+ assert is_size_exempt(path) is exempt
+
+
+def test_substantive_size_counts_only_non_exempt_files() -> None:
+ # A docs-heavy PR must not be size-denied for its prose, and a code-heavy
+ # PR must not slip under the ceiling by padding with docs.
+ files = [
+ {"filename": "docs/big-rewrite.md", "additions": 2000, "deletions": 500},
+ {"filename": "frontend/src/generated/core/api.ts", "additions": 900, "deletions": 900},
+ {"filename": "posthog/api/insight.py", "additions": 30, "deletions": 10},
+ {"filename": "posthog/api/test/test_insight.py", "additions": 50, "deletions": 0},
+ ]
+
+ lines, file_count = substantive_size(files)
+
+ assert lines == 90
+ assert file_count == 2
diff --git a/tools/pr-approval-agent/test_github.py b/tools/pr-approval-agent/test_github.py
index e9299fcf6c8d..1c821e81865c 100644
--- a/tools/pr-approval-agent/test_github.py
+++ b/tools/pr-approval-agent/test_github.py
@@ -181,3 +181,65 @@ def test_review_threads_query_stays_under_github_node_limit() -> None:
# GitHub rejects any GraphQL query whose worst-case node count exceeds
# 500,000 before executing it, which hard-fails the review on every PR.
assert _worst_case_node_count(github._REVIEW_THREADS_QUERY) < 500_000
+
+
+ "login,expected_users",
+ [
+ pytest.param("stamphog[bot]", ["greptile-apps[bot]"], id="own-inline-comment-excluded"),
+ pytest.param("github-actions[bot]", ["greptile-apps[bot]"], id="own-approve-identity-excluded"),
+ pytest.param(
+ "copilot-pull-request-reviewer[bot]",
+ ["copilot-pull-request-reviewer[bot]", "greptile-apps[bot]"],
+ id="other-bot-kept",
+ ),
+ ],
+)
+def test_fetch_threads_excludes_stamphogs_own_inline_comments(
+ monkeypatch: pytest.MonkeyPatch, login: str, expected_users: list[str]
+) -> None:
+ # Stamphog's earlier verdicts fed back through inline comments read as
+ # third-party claims about a stale snapshot — later runs then suspect
+ # impersonation and refuse forever, exactly like stale top-level reviews.
+ def fake_graphql(query: str, variables: dict | None = None) -> dict:
+ def comment(user: str) -> dict:
+ return {
+ "author": {"login": user, "__typename": "Bot"},
+ "authorAssociation": "NONE",
+ "body": f"comment from {user}",
+ "databaseId": 1,
+ "replyTo": None,
+ "reactions": {"nodes": []},
+ }
+
+ return {
+ "data": {
+ "repository": {
+ "pullRequest": {
+ "reactions": {"nodes": []},
+ "reviewThreads": {
+ "pageInfo": {"hasNextPage": False, "endCursor": None},
+ "nodes": [
+ {
+ "isResolved": False,
+ "isOutdated": False,
+ "path": "posthog/api/insight.py",
+ "line": 42,
+ "comments": {
+ "pageInfo": {"hasNextPage": False},
+ "nodes": [comment(login), comment("greptile-apps[bot]")],
+ },
+ }
+ ],
+ },
+ }
+ }
+ }
+ }
+
+ monkeypatch.setattr(github, "_gh_graphql", fake_graphql)
+ monkeypatch.setattr(github, "_is_org_member", lambda org, member: False)
+
+ comments, _ = github._fetch_threads_and_reactions("PostHog/posthog", 1, author="alice")
+
+ assert [c["user"] for c in comments] == expected_users
diff --git a/tools/pr-approval-agent/test_review_pr.py b/tools/pr-approval-agent/test_review_pr.py
index 97953a872716..d7d10680b9d0 100644
--- a/tools/pr-approval-agent/test_review_pr.py
+++ b/tools/pr-approval-agent/test_review_pr.py
@@ -176,3 +176,134 @@ def test_bot_author_refuses_before_classification(monkeypatch: pytest.MonkeyPatc
assert output["final_verdict"] == "REFUSED"
assert output["classification"]["tier"] == ""
assert output["classification"]["breadth"] == ""
+
+
+# ── In-flight bot review handling ────────────────────────────────
+
+
+ "reactions",
+ [
+ pytest.param([], id="no-reactions"),
+ pytest.param([{"user": "greptile-apps[bot]", "emoji": "👍"}], id="bot-verdict-reaction"),
+ pytest.param([{"user": "alice", "emoji": "👀"}], id="human-eyes-not-waited-on"),
+ pytest.param(
+ [{"user": "greptile-apps[bot]", "emoji": "👀", "created_at": "2020-01-01T00:00:00Z"}],
+ id="stale-bot-eyes-from-crashed-reviewer-ignored",
+ ),
+ ],
+)
+def test_no_wait_without_in_flight_bot_review(monkeypatch: pytest.MonkeyPatch, reactions: list[dict]) -> None:
+ # Waiting on a human 👀 would block for longer than any polling budget —
+ # the LLM refuses over those instead — and waiting with nothing in flight
+ # would slow every review down.
+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+ monkeypatch.setattr(review_pr.time, "sleep", lambda _s: pytest.fail("must not poll"))
+
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="abc123")
+ pipeline.pr.pr_reactions = reactions
+
+ assert pipeline._handle_in_flight_bot_reviews() is None
+ assert pipeline.final_verdict == ""
+
+
+def test_waits_out_bot_eyes_race_then_proceeds(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Reviewer bots swap 👀 for a verdict reaction within minutes; refusing
+ # during that window was ~26% of all denials in the week this landed.
+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+ monkeypatch.setattr(review_pr.time, "sleep", lambda _s: None)
+
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ pr = _fake_pr(head_sha="abc123")
+ pr.pr_reactions = [{"user": "greptile-apps[bot]", "emoji": "👀"}]
+ pipeline.pr = pr
+
+ def fake_refetch() -> None:
+ pr.pr_reactions = [{"user": "greptile-apps[bot]", "emoji": "👍"}]
+
+ monkeypatch.setattr(pipeline, "_fetch", fake_refetch)
+
+ assert pipeline._handle_in_flight_bot_reviews() is None
+ assert pipeline.final_verdict == ""
+
+
+def test_persistent_bot_eyes_yields_wait_not_refuse(monkeypatch: pytest.MonkeyPatch) -> None:
+ # WAIT keeps the stamphog label (workflow skips the label-strip for it),
+ # so a slow bot review retries on the next push instead of demanding a
+ # human re-label — a REFUSE here would reintroduce the race friction.
+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+ monkeypatch.setattr(review_pr, "BOT_REVIEW_WAIT_BUDGET_SECONDS", 0)
+ monkeypatch.setattr(review_pr.time, "sleep", lambda _s: None)
+
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="abc123")
+ pipeline.pr.pr_reactions = [{"user": "hex-security-app[bot]", "emoji": "👀"}]
+
+ assert pipeline._handle_in_flight_bot_reviews() == "WAIT"
+ assert pipeline.final_verdict == "WAIT"
+ assert pipeline.reviewer_output is not None
+ assert pipeline.reviewer_output["verdict"] == "WAIT"
+ assert "hex-security-app[bot]" in pipeline.reviewer_output["reasoning"]
+
+ output = pipeline.to_dict()
+ assert output["final_verdict"] == "WAIT"
+
+
+def test_gate_denied_pr_skips_the_wait(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A deny-listed PR can't be approved over an in-flight review, so waiting
+ # 5 minutes before the inevitable REFUSE is pure runner cost.
+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+ monkeypatch.setattr(review_pr.time, "sleep", lambda _s: pytest.fail("gate-denied PR must not wait"))
+
+ class _RefusingReviewer:
+ def __init__(self, *args: object, **kwargs: object) -> None:
+ pass
+
+ def review(self, *args: object, **kwargs: object) -> dict:
+ return {"verdict": "REFUSE", "reasoning": "gates denied", "risk": "high", "issues": []}
+
+ monkeypatch.setattr(review_pr, "Reviewer", _RefusingReviewer)
+
+ pr = _fake_pr(head_sha="abc123")
+ pr.files = [{"filename": ".github/workflows/ci.yml", "additions": 2, "deletions": 1, "status": "M"}]
+ pr.pr_reactions = [{"user": "greptile-apps[bot]", "emoji": "👀"}]
+
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ monkeypatch.setattr(pipeline, "_fetch", lambda: setattr(pipeline, "pr", pr))
+
+ assert pipeline.run() == "REFUSED"
+
+
+def test_wait_refetch_reclassifies_before_review(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The wait loop refetches the PR; if the author pushed during the wait,
+ # gates must run against the new file set, not the pre-wait snapshot.
+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+ monkeypatch.setattr(review_pr.time, "sleep", lambda _s: None)
+
+ class _ApprovingReviewer:
+ def __init__(self, *args: object, **kwargs: object) -> None:
+ pass
+
+ def review(self, *args: object, **kwargs: object) -> dict:
+ return {"verdict": "APPROVE", "reasoning": "ok", "risk": "low", "issues": []}
+
+ monkeypatch.setattr(review_pr, "Reviewer", _ApprovingReviewer)
+
+ initial = _fake_pr(head_sha="abc123")
+ initial.files = [{"filename": "docs/readme.md", "additions": 1, "deletions": 0, "status": "M"}]
+ initial.pr_reactions = [{"user": "greptile-apps[bot]", "emoji": "👀"}]
+
+ refetched = _fake_pr(head_sha="def456")
+ refetched.files = [{"filename": ".github/workflows/ci.yml", "additions": 2, "deletions": 1, "status": "M"}]
+ refetched.pr_reactions = []
+
+ fetches = iter([initial, refetched])
+
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ monkeypatch.setattr(pipeline, "_fetch", lambda: setattr(pipeline, "pr", next(fetches)))
+
+ verdict = pipeline.run()
+
+ assert verdict == "REFUSED"
+ assert pipeline.classification["deny_categories"] == ["infra_cicd"]