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.

fix(stamphog): close deferred approval-integrity and review-context gaps (#71544)

Julian Bez25a292f5b142
diff --git a/.dockerignore b/.dockerignore
index 904a63fe1be8..8fb9cdba8b6d 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -86,6 +86,7 @@ services/agent-tests
!tools/hogli
!tools/openapi-codegen
!tools/owners
+!tools/pr-approval-agent
!tsconfig.json
!unit.json.tpl
common/*/*/node_modules
diff --git a/Dockerfile b/Dockerfile
index d08b42db1f87..2cfe99494aa4 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -409,6 +409,11 @@ COPY --chown=posthog:posthog common/hogvm common/hogvm/
COPY --chown=posthog:posthog common/migration_utils common/migration_utils/
COPY --chown=posthog:posthog common/alerting common/alerting/
COPY --chown=posthog:posthog products products/
+# Stamphog ships the review engine + owners resolver from this checkout into its sandbox at
+# runtime (products/stamphog/backend/temporal/activities.py), so both must exist in the image.
+COPY --chown=posthog:posthog tools/pr-approval-agent tools/pr-approval-agent/
+COPY --chown=posthog:posthog tools/owners tools/owners/
+RUN test -f tools/pr-approval-agent/review_local.py && test -d tools/owners/posthog_owners
# Generated MCP tool catalog, read at runtime from BASE_DIR by the OAuth consent page
# (posthog/api/oauth/mcp_resource_scopes.py) and the tasks permission broker. The rest of
# services/ is a Node build (Dockerfile.node) and deliberately stays out of this image.
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index f5b9dec931b0..7f9b042b5dff 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -44,7 +44,7 @@ GITHUB_APP_CLIENT_SECRET = get_from_env("GITHUB_APP_CLIENT_SECRET", "")
# webhook secret. Empty defaults keep the app importable when Stamphog is unconfigured.
STAMPHOG_GITHUB_APP_ID = get_from_env("STAMPHOG_GITHUB_APP_ID", "")
STAMPHOG_GITHUB_APP_PRIVATE_KEY = get_from_env("STAMPHOG_GITHUB_APP_PRIVATE_KEY", "")
-STAMPHOG_GITHUB_WEBHOOK_SECRET = get_from_env("STAMPHOG_GITHUB_WEBHOOK_SECRET", "")
+STAMPHOG_GITHUB_APP_WEBHOOK_SECRET = get_from_env("STAMPHOG_GITHUB_APP_WEBHOOK_SECRET", "")
# OAuth client id/secret for the Stamphog App's user-to-server authorization flow (enabled via
# "Request user authorization during installation"). Used to exchange the post-install `code` for a
# user access token and prove the caller actually owns the installation before its repos are bound to
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 41f3ebef61e6..9e8a33bbe980 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -20,9 +20,27 @@ head-changing event must retract standing approvals itself:
`_retract_stale_approvals_on_skip`.
- `post_verdict` persists `posted_review_id` the moment GitHub accepts the review, and any path
that abandons the run _after_ posting (lost terminal save, superseded/head-moved guards on
- retry) dismisses its own orphan (`_dismiss_orphaned_approval`).
+ retry) dismisses its own orphan (`_dismiss_orphaned_approval`). Before posting it also
+ ADOPTS-then-persists: if this App already has an active APPROVE pinned to exactly `run.head_sha`
+ on GitHub (a prior attempt that posted, then crashed before the immediate persist), it takes that
+ review's id instead of stacking a second approval the DB-keyed sweep could never see.
- The sweep in [`logic/approvals.py`](backend/logic/approvals.py) keys off `posted_review_id`
alone — filtering on a saved verdict would miss crashed runs' orphans.
+- `dismiss_stale_approvals` also runs a GitHub-side belt-and-braces sweep after the DB sweep: it
+ lists this App's still-active APPROVED reviews and dismisses every one regardless of head, catching
+ an orphan that has no `ReviewRun` row at all (the DB sweep is blind to it). Both write-adjacent
+ paths (this sweep and `post_verdict`'s adopt) identify "ours" via the exact `<slug>[bot]` login and
+ do NOTHING when `STAMPHOG_GITHUB_APP_SLUG` is unset — a fuzzy "any Bot" match must never dismiss or
+ adopt another bot's review.
+- A run that reaches a **non-approve terminal** (`post_verdict`'s gated/refused/escalate/wait branch,
+ or `mark_review_failed`) re-runs the GitHub-side own-approvals sweep at its own end
+ (`_sweep_orphan_approvals_at_terminal`). This closes the supersession race: an older run can clear
+ `post_verdict`'s final guards, get superseded, then land its GitHub approval AFTER the newer run's
+ STARTUP sweep — and if the newer run refuses (or fails), nothing lists our approvals again, so the
+ orphan stands over a refusing verdict. The keep-set excludes every OTHER live run's persisted
+ `posted_review_id` (writer-pinned read), so a slow run at terminal never dismisses a newer run's
+ legit approval. UNLIKE the fail-closed startup sweep, the terminal sweep is fail-open: a GitHub error
+ must not block the terminal save (the integrity gap on error is the pre-existing exposure, no worse).
## Supersession and terminal states
diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.py
index c7ae198ebd11..8e0eb7e05fec 100644
--- a/products/stamphog/backend/logic/github_client.py
+++ b/products/stamphog/backend/logic/github_client.py
@@ -1,7 +1,8 @@
"""Dedicated GitHub App client for Stamphog.
Stamphog runs as its own GitHub App (separate identity from PostHog's product-integration App), so it
-mints its own installation tokens from ``STAMPHOG_GITHUB_APP_ID`` / ``STAMPHOG_GITHUB_APP_PRIVATE_KEY``.
+mints its own installation tokens from ``STAMPHOG_GITHUB_APP_CLIENT_ID`` (or ``STAMPHOG_GITHUB_APP_ID``
+as a fallback) / ``STAMPHOG_GITHUB_APP_PRIVATE_KEY``.
Every outbound call goes through the shared egress transport (:func:`posthog.egress.github.transport.github_request`),
which gates on the installation's shared budget and records telemetry by construction. That transport is
token-agnostic and stateless, so a second App identity needs no change to the egress layer — this client
@@ -36,40 +37,127 @@ _SOURCE = "stamphog"
STICKY_COMMENT_MARKER = "<!-- stamphog:review-status -->"
-def _expected_sticky_comment_login() -> str | None:
- """The GitHub login the App posts sticky comments under (``<slug>[bot]``), or None if unconfigured.
+def expected_app_bot_login() -> str | None:
+ """The GitHub login this App acts under (``<slug>[bot]``), or None if the slug is unconfigured.
- GitHub App comments are authored by ``<app-slug>[bot]`` with ``user.type == "Bot"``. When we know
- the slug we can require that exact identity; when it isn't configured we fall back to "any Bot".
+ GitHub App reviews and comments are authored by ``<app-slug>[bot]`` with ``user.type == "Bot"``.
+ When we know the slug we can require that exact identity; when it isn't configured, callers decide
+ whether "any Bot" is an acceptable floor (see ``_is_own_bot_actor``'s ``allow_any_bot``). Public
+ (not underscore-prefixed) because the in-flight reviewer-bot wait in ``temporal/activities.py``
+ needs it too, to exclude stamphog's own 👀 reaction from the trusted-bot reactor set it reads.
"""
slug = settings.STAMPHOG_GITHUB_APP_SLUG
return f"{slug}[bot]" if slug else None
-def _is_own_sticky_comment(comment: dict, expected_login: str | None) -> bool:
- """Whether ``comment`` was posted by this App, not just any account carrying the marker.
+def _is_own_bot_actor(user: dict, expected_login: str | None, *, allow_any_bot: bool) -> bool:
+ """Whether ``user`` (a review's or comment's author object) is this App's own bot identity.
- The marker is visible in the rendered comment source, so a user could plant it to trick a naive
- upsert into PATCHing (hijacking) their comment. Require a Bot author, and — when we know our slug —
- the exact ``<slug>[bot]`` login. Without a configured slug, "type == Bot" is the minimum floor.
+ The identity floor: a Bot author, and — when the App slug is configured — the exact ``<slug>[bot]``
+ login. ``allow_any_bot`` decides the unconfigured-slug case. Sticky-comment upserts tolerate the
+ "any Bot" fallback (a mis-targeted PATCH is cosmetic). Write-adjacent approval decisions
+ (adopt-before-post, the GitHub-side orphan sweep) must NOT: dismissing or adopting another bot's
+ review off a fuzzy match is worse than doing nothing, so they pass ``allow_any_bot=False`` and get
+ nothing without a slug. Reviews and comments carry the same ``user`` shape, so this serves both.
"""
- user = comment.get("user") or {}
if user.get("type") != "Bot":
return False
if expected_login is not None:
- return (user.get("login") or "") == expected_login
- return True
+ # Case-insensitive like every GitHub login comparison (and the reactor-bot exclusion): a raw
+ # == would silently no-op the sweeps and adopt if GitHub ever cases the login differently.
+ return (user.get("login") or "").lower() == expected_login.lower()
+ return allow_any_bot
+
+
+def _is_own_sticky_comment(comment: dict, expected_login: str | None) -> bool:
+ """Whether ``comment`` was posted by this App, not just any account carrying the marker.
+
+ The marker is visible in the rendered comment source, so a user could plant it to trick a naive
+ upsert into PATCHing (hijacking) their comment. The "any Bot" fallback is acceptable here — a
+ mis-targeted sticky PATCH is cosmetic, never a standing approval (contrast the approval paths).
+ """
+ return _is_own_bot_actor(comment.get("user") or {}, expected_login, allow_any_bot=True)
# Cap on how many comment/file pages we page through, so a pathological PR can't spin forever.
_MAX_PAGES = 20
_PER_PAGE = 100
+# Trim each inline review-thread comment body to bound the payload that rides in run.output. The
+# reviewer only needs the gist of a maintainer's "do not merge", not a novel.
+_REVIEW_THREAD_BODY_MAX = 4000
+
+# reviewThreads(first: 100) × comments(first: 50) is 5,000 worst-case nodes — far under GitHub's
+# 500,000 pre-execution node cap. Only the fields the hosted reviewer needs: resolution state,
+# path/line, and per comment the author identity triple (login, association, Bot-ness) the engine's
+# author-trust gate requires plus the body. The comments pageInfo detects per-thread overflow —
+# a >50-comment thread pages its tail via _THREAD_COMMENTS_QUERY (comment 51 could be a
+# maintainer's hold, and failing the whole review would make one chatty thread block the PR
+# forever), failing closed only past the per-thread page cap.
+_REVIEW_THREADS_QUERY = """
+query($owner: String!, $name: String!, $pr: Int!, $cursor: String) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $pr) {
+ reviewThreads(first: 100, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ nodes {
+ id
+ isResolved
+ isOutdated
+ path
+ line
+ comments(first: 50) {
+ pageInfo { hasNextPage endCursor }
+ nodes {
+ author { login __typename }
+ authorAssociation
+ body
+ }
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+# Tail pages for a single thread whose comments overflow the window above.
+_THREAD_COMMENTS_QUERY = """
+query($id: ID!, $cursor: String) {
+ node(id: $id) {
+ ... on PullRequestReviewThread {
+ comments(first: 50, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ nodes {
+ author { login __typename }
+ authorAssociation
+ body
+ }
+ }
+ }
+ }
+}
+"""
+
# Refresh the installation token this many seconds before GitHub's stated expiry, to cover clock skew
# and in-flight requests. GitHub installation tokens live one hour, so a 5-minute margin is ample.
_TOKEN_EXPIRY_MARGIN_SECONDS = 300
+def _parse_review_thread_comments(comment_nodes: list) -> list[dict]:
+ """Normalize GraphQL review-thread comment nodes to the engine's shape (both queries share it)."""
+ return [
+ {
+ "author": (comment.get("author") or {}).get("login") or "",
+ "author_association": comment.get("authorAssociation") or "",
+ "author_is_bot": (comment.get("author") or {}).get("__typename") == "Bot",
+ "body": (comment.get("body") or "")[:_REVIEW_THREAD_BODY_MAX],
+ }
+ for comment in comment_nodes
+ if isinstance(comment, dict)
+ ]
+
+
class StamphogGitHubError(Exception):
"""A Stamphog GitHub API call failed for a non-rate-limit reason (auth failure, unexpected status,
malformed response). Rate limits raise ``GitHubRateLimitError`` from the egress layer instead."""
@@ -91,15 +179,19 @@ def _build_app_jwt() -> str:
"""Build a short-lived App JWT (RS256) for minting installation tokens.
``iat`` is backdated 60s to tolerate clock skew against GitHub; ``exp`` stays inside GitHub's
- 10-minute maximum. The App id is the issuer.
+ 10-minute maximum. The client id is the issuer — the same form the core GitHub integration
+ signs with (see ``posthog.models.github_integration_base``).
"""
- app_id = settings.STAMPHOG_GITHUB_APP_ID
- if not app_id:
- raise StamphogGitHubError("STAMPHOG_GITHUB_APP_ID is not configured")
+ # Client id is the preferred issuer (matches the core GitHub integration); the app id fallback
+ # covers workers whose chart predates the client id env. Drop the fallback once every worker
+ # deploy ships STAMPHOG_GITHUB_APP_CLIENT_ID.
+ issuer = settings.STAMPHOG_GITHUB_APP_CLIENT_ID or settings.STAMPHOG_GITHUB_APP_ID
+ if not issuer:
+ raise StamphogGitHubError("Neither STAMPHOG_GITHUB_APP_CLIENT_ID nor STAMPHOG_GITHUB_APP_ID is configured")
now = int(time.time())
try:
return jwt.encode(
- {"iat": now - 60, "exp": now + 540, "iss": str(app_id)},
+ {"iat": now - 60, "exp": now + 540, "iss": str(issuer)},
_app_private_key(),
algorithm="RS256",
)
@@ -150,15 +242,17 @@ def exchange_oauth_code_for_user_token(code: str) -> str | None:
return str(access_token)
-def user_can_access_installation(installation_id: str, user_access_token: str) -> bool:
- """Whether the OAuth'd user can reach the given App installation.
+def list_user_installations(user_access_token: str) -> list[dict[str, str]]:
+ """This App's installations the OAuth'd user can reach, as ``[{"id", "account_login"}, ...]``.
- Lists the installations visible to the *user's* token (``GET /user/installations``) and checks the
- submitted id is among them. Authenticated with the user token, so it is identity-blind on the egress
- budget (no ``installation_id`` passed to the gate) — GitHub meters it against the user, not the
- installation. Raises :class:`StamphogGitHubError` on an unexpected status so the caller fails closed
- rather than silently treating an API hiccup as "no access".
+ Pages ``GET /user/installations`` with the *user's* token, which GitHub scopes to installations of
+ THIS App the user can access — the discovery primitive for the authorize-first connect flow, where
+ no installation_id rides in the callback. Authenticated with the user token, so it is identity-blind
+ on the egress budget (no ``installation_id`` passed to the gate) — GitHub meters it against the user,
+ not the installation. Raises :class:`StamphogGitHubError` on an unexpected status so the caller fails
+ closed rather than silently treating an API hiccup as "no installations".
"""
+ installations: list[dict[str, str]] = []
for page in range(1, _MAX_PAGES + 1):
response = github_request(
"GET",
@@ -178,15 +272,33 @@ def user_can_access_installation(installation_id: str, user_access_token: str) -
data = response.json()
except ValueError as exc:
raise StamphogGitHubError("Non-JSON response listing user installations") from exc
- installations = data.get("installations") if isinstance(data, dict) else None
- if not isinstance(installations, list):
+ page_installations = data.get("installations") if isinstance(data, dict) else None
+ if not isinstance(page_installations, list):
raise StamphogGitHubError("Unexpected user installations payload")
- for installation in installations:
- if isinstance(installation, dict) and str(installation.get("id")) == str(installation_id):
- return True
- if len(installations) < _PER_PAGE:
+ for installation in page_installations:
+ if not isinstance(installation, dict) or installation.get("id") is None:
+ continue
+ installations.append(
+ {
+ "id": str(installation.get("id")),
+ "account_login": ((installation.get("account") or {}).get("login") or ""),
+ }
+ )
+ if len(page_installations) < _PER_PAGE:
break
- return False
+ return installations
+
+
+def user_can_access_installation(installation_id: str, user_access_token: str) -> bool:
+ """Whether the OAuth'd user can reach the given App installation.
+
+ Built on :func:`list_user_installations`: the submitted id must be among the installations visible to
+ the user's token. Raises :class:`StamphogGitHubError` on an unexpected status (via the underlying
+ call) so the caller fails closed rather than silently treating an API hiccup as "no access".
+ """
+ return any(
+ installation["id"] == str(installation_id) for installation in list_user_installations(user_access_token)
+ )
def list_user_accessible_repositories(installation_id: str, user_access_token: str) -> list[str]:
@@ -399,6 +511,73 @@ class StamphogGitHubClient:
f"Reactions on {repo}#{number} exceed {_MAX_PAGES * _PER_PAGE}; refusing to evaluate a truncated list"
)
+ def add_pr_reaction(self, repo: str, number: int, content: str = "eyes") -> int | None:
+ """Add a reaction to the PR itself (``POST .../issues/{number}/reactions``), returning its id.
+
+ Fail-open, UNLIKE every other method on this client: an 👀 reaction is the same cosmetic
+ "review in flight" signal ``get_pr_reactions``/``STAMPHOG_TRUSTED_REACTOR_BOTS`` reads off
+ other bots, never a gate on anything. A failed reaction post must never fail or retry the
+ calling review activity, so every exception and non-2xx response is caught and logged here
+ instead of raised — callers get ``None`` and carry on. GitHub itself returns 200 with the
+ EXISTING reaction if this identity already reacted with ``content`` on this target (natural
+ idempotency: a retried activity, or adopting a crashed predecessor's leftover reaction), or
+ 201 with a freshly created one — either way the id is what callers persist to remove later.
+ """
+ path = f"/repos/{repo}/issues/{number}/reactions"
+ try:
+ response = self._request(
+ "POST",
+ path,
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/reactions",
+ json_body={"content": content},
+ )
+ except Exception:
+ logger.warning("stamphog github: failed to add PR reaction", repo=repo, pr_number=number, exc_info=True)
+ return None
+ if response.status_code not in (200, 201):
+ logger.warning(
+ "stamphog github: unexpected status adding PR reaction",
+ repo=repo,
+ pr_number=number,
+ status_code=response.status_code,
+ )
+ return None
+ try:
+ data = self._json(response, path)
+ except StamphogGitHubError:
+ logger.warning("stamphog github: non-JSON response adding PR reaction", repo=repo, pr_number=number)
+ return None
+ reaction_id = data.get("id") if isinstance(data, dict) else None
+ return reaction_id if isinstance(reaction_id, int) else None
+
+ def remove_pr_reaction(self, repo: str, number: int, reaction_id: int) -> None:
+ """Remove a reaction from the PR itself (``DELETE .../issues/{number}/reactions/{reaction_id}``).
+
+ Fail-open like ``add_pr_reaction``, for the same reason: this only cleans up the cosmetic
+ "review in flight" 👀, so a failure here must never fail or retry the calling activity — a
+ leftover reaction is harmless (the next run's ``add_pr_reaction`` adopts it via GitHub's own
+ idempotency). Every exception and non-2xx response is caught and logged instead of raised.
+ A 404 means the reaction is already gone (a prior attempt succeeded before crashing, or
+ someone removed it by hand) and is treated the same as success.
+ """
+ path = f"/repos/{repo}/issues/{number}/reactions/{reaction_id}"
+ try:
+ response = self._request(
+ "DELETE",
+ path,
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}",
+ )
+ except Exception:
+ logger.warning("stamphog github: failed to remove PR reaction", repo=repo, pr_number=number, exc_info=True)
+ return
+ if response.status_code not in (200, 204, 404):
+ logger.warning(
+ "stamphog github: unexpected status removing PR reaction",
+ repo=repo,
+ pr_number=number,
+ status_code=response.status_code,
+ )
+
def get_collaborator_permission(self, repo: str, username: str) -> str:
"""The user's effective permission on the repo: ``admin``, ``write``, ``read``, or ``none``.
@@ -450,7 +629,7 @@ class StamphogGitHubClient:
Returns the raw GitHub review objects (``user``, ``state``, ``commit_id``, ``body``,
``author_association``, ...). The reviewer engine needs these to honor an active
``CHANGES_REQUESTED`` review — without them the hosted path would run review-blind and could
- approve over a maintainer's block. Stops at ``_MAX_PAGES`` for the same bound as the other lists.
+ approve over a maintainer's block. Fails closed past ``_MAX_PAGES`` — the orphan sweeps ride this list, and a silently truncated tail could hide an approval they must dismiss.
"""
reviews: list[dict] = []
for page in range(1, _MAX_PAGES + 1):
@@ -470,8 +649,46 @@ class StamphogGitHubClient:
raise StamphogGitHubError(f"Unexpected PR reviews payload for {repo}#{number}")
reviews.extend(review for review in page_reviews if isinstance(review, dict))
if len(page_reviews) < _PER_PAGE:
- break
- return reviews
+ return reviews
+ # Past the cap the tail is invisible — and list_own_active_approvals rides this list for the
+ # orphan sweeps, where a silently missing approval defeats the guarantee. Fail closed like
+ # the thread fetch rather than pretending the truncated list is complete.
+ raise StamphogGitHubError(
+ f"PR reviews on {repo}#{number} exceed {_MAX_PAGES} pages; refusing to act on a truncated list"
+ )
+
+ def list_own_active_approvals(self, repo: str, number: int) -> list[dict]:
+ """Active APPROVE reviews on the PR authored by THIS App, as raw GitHub review dicts.
+
+ Built on ``get_pr_reviews``' pagination. "Active APPROVED" means ``state == "APPROVED"`` — GitHub
+ reports a dismissed review as state ``DISMISSED``, so those drop out on their own. Identity uses
+ the same floor as the sticky-comment path but WITHOUT the "any Bot" fallback: this feeds
+ write-adjacent decisions (adopt-before-post in ``post_verdict``, the GitHub-side orphan sweep in
+ ``dismiss_stale_approvals``), where acting on another bot's review off a fuzzy match is worse than
+ doing nothing — so an unconfigured ``STAMPHOG_GITHUB_APP_SLUG`` yields an empty list, never a guess.
+ Callers filter further (e.g. adopt only at an exact ``commit_id``); the raw dicts carry ``id`` and
+ ``commit_id`` for that.
+ """
+ expected_login = expected_app_bot_login()
+ if expected_login is None:
+ # Loud on purpose: with App credentials configured but no slug, approvals still POST fine
+ # while every GitHub-side sweep and adopt silently no-ops — quietly disabling the
+ # orphan-catching half of the stale-approval invariant. The misconfiguration would
+ # otherwise be invisible until an orphan approval stands over unreviewed commits.
+ if settings.STAMPHOG_GITHUB_APP_PRIVATE_KEY:
+ logger.warning(
+ "stamphog github: STAMPHOG_GITHUB_APP_SLUG unset with App credentials configured — "
+ "own-approval sweeps and adopt-before-post are disabled",
+ repo=repo,
+ pr_number=number,
+ )
+ return []
+ return [
+ review
+ for review in self.get_pr_reviews(repo, number)
+ if review.get("state") == "APPROVED"
+ and _is_own_bot_actor(review.get("user") or {}, expected_login, allow_any_bot=False)
+ ]
def get_pr_discussion(self, repo: str, number: int) -> list[dict]:
"""Fetch the PR's top-level discussion (issue) comments, paginating through GitHub's endpoint.
@@ -479,7 +696,7 @@ class StamphogGitHubClient:
Returns raw GitHub issue-comment objects (``user``, ``body``, ``author_association``, ...). The
reviewer uses these as blocker context — a maintainer's top-level "please hold" comment should
reach the agent, matching the Action path. Inline review-thread comments are a separate,
- GraphQL-only surface (thread resolution state) and are not fetched here. Past the page cap the
+ GraphQL-only surface (thread resolution state) fetched by ``get_pr_review_threads``. Past the page cap the
fetch fails closed (raises) like the reactions fetch: anyone can comment on a public PR, so an
author could bury a maintainer's hold past the cap and a silently truncated list would read as
"no blockers" to the reviewer.
@@ -508,6 +725,125 @@ class StamphogGitHubClient:
"refusing to review with a truncated discussion"
)
+ def get_pr_review_threads(self, repo: str, number: int) -> list[dict]:
+ """Fetch the PR's inline review threads via GraphQL, as
+ ``[{is_resolved, is_outdated, path, line,
+ comments: [{author, author_association, author_is_bot, body}]}]``.
+
+ Each comment carries the author identity triple (login, association, Bot-ness) because the
+ engine gates inline comments through the same author-trust check as reviews and discussion —
+ without it, an untrusted external commenter could plant a fake maintainer hold in the prompt.
+
+ Inline review-thread comments are a GraphQL-only surface — REST exposes no thread-resolution
+ state — so the hosted reviewer would otherwise be blind to a maintainer's unresolved inline
+ "this is wrong, do not merge". Follows ``get_user_team_slugs``' ``/graphql`` request shape but NOT
+ its best-effort error handling: FAILS CLOSED like ``get_pr_discussion`` — raises past the page cap
+ or on any GraphQL/HTTP/parse failure — because a silently truncated thread list reads as "no
+ blockers" to the reviewer, the one wrong answer here. Comment bodies are trimmed to bound the
+ payload that rides in ``run.output``.
+ """
+ if "/" not in repo:
+ raise StamphogGitHubError(f"Expected an owner/name repo, got {repo!r}")
+ owner, name = repo.split("/", 1)
+ threads: list[dict] = []
+ cursor: str | None = None
+ for _page in range(_MAX_PAGES):
+ response = self._request(
+ "POST",
+ "/graphql",
+ endpoint="/graphql",
+ json_body={
+ "query": _REVIEW_THREADS_QUERY,
+ "variables": {"owner": owner, "name": name, "pr": number, "cursor": cursor},
+ },
+ )
+ if response.status_code != 200:
+ raise StamphogGitHubError(
+ f"Failed to fetch review threads for {repo}#{number}: {response.text[:300]}",
+ status_code=response.status_code,
+ )
+ data = self._json(response, "/graphql")
+ if not isinstance(data, dict) or data.get("errors"):
+ raise StamphogGitHubError(f"GraphQL errors fetching review threads for {repo}#{number}")
+ pull_request = ((data.get("data") or {}).get("repository") or {}).get("pullRequest")
+ if not isinstance(pull_request, dict):
+ raise StamphogGitHubError(f"Unexpected review-threads payload for {repo}#{number}")
+ review_threads = pull_request.get("reviewThreads") or {}
+ for node in review_threads.get("nodes") or []:
+ if not isinstance(node, dict):
+ continue
+ comment_page = node.get("comments") or {}
+ comments = _parse_review_thread_comments(comment_page.get("nodes") or [])
+ comment_page_info = comment_page.get("pageInfo") or {}
+ # A thread past the comments fetch window pages its tail — silently dropping
+ # comment 51 could hide a maintainer's hold, and failing the run outright would
+ # make one chatty thread block the PR from ever being reviewed.
+ if comment_page_info.get("hasNextPage"):
+ comments.extend(
+ self._fetch_remaining_thread_comments(
+ repo, number, node.get("id"), comment_page_info.get("endCursor")
+ )
+ )
+ threads.append(
+ {
+ "is_resolved": bool(node.get("isResolved")),
+ "is_outdated": bool(node.get("isOutdated")),
+ "path": node.get("path") or "",
+ "line": node.get("line"),
+ "comments": comments,
+ }
+ )
+ page_info = review_threads.get("pageInfo") or {}
+ if not page_info.get("hasNextPage"):
+ return threads
+ cursor = page_info.get("endCursor")
+ raise StamphogGitHubError(
+ f"Review threads on {repo}#{number} exceed {_MAX_PAGES} pages; refusing to review a truncated list"
+ )
+
+ def _fetch_remaining_thread_comments(
+ self, repo: str, number: int, thread_id: str | None, cursor: str | None
+ ) -> list[dict]:
+ """Page the tail of one review thread whose comments overflow the main query's window.
+
+ Same fail-closed posture as the caller: any HTTP/GraphQL/parse failure raises, and a thread
+ that still overflows ``_MAX_PAGES`` tail pages (thousands of comments — pathological) raises
+ rather than returning a truncated thread the reviewer would read as complete.
+ """
+ if not thread_id:
+ raise StamphogGitHubError(
+ f"A review thread on {repo}#{number} overflows its comment window but carries no node id"
+ )
+ collected: list[dict] = []
+ for _page in range(_MAX_PAGES):
+ response = self._request(
+ "POST",
+ "/graphql",
+ endpoint="/graphql",
+ json_body={"query": _THREAD_COMMENTS_QUERY, "variables": {"id": thread_id, "cursor": cursor}},
+ )
+ if response.status_code != 200:
+ raise StamphogGitHubError(
+ f"Failed to fetch thread comments for {repo}#{number}: {response.text[:300]}",
+ status_code=response.status_code,
+ )
+ data = self._json(response, "/graphql")
+ if not isinstance(data, dict) or data.get("errors"):
+ raise StamphogGitHubError(f"GraphQL errors fetching thread comments for {repo}#{number}")
+ thread_node = (data.get("data") or {}).get("node")
+ if not isinstance(thread_node, dict):
+ raise StamphogGitHubError(f"Unexpected thread-comments payload for {repo}#{number}")
+ comment_page = thread_node.get("comments") or {}
+ collected.extend(_parse_review_thread_comments(comment_page.get("nodes") or []))
+ page_info = comment_page.get("pageInfo") or {}
+ if not page_info.get("hasNextPage"):
+ return collected
+ cursor = page_info.get("endCursor")
+ raise StamphogGitHubError(
+ f"A review thread on {repo}#{number} exceeds {_MAX_PAGES} comment pages; "
+ "refusing to review a truncated thread"
+ )
+
def get_check_runs(self, repo: str, head_sha: str) -> list[dict]:
"""Fetch the check runs for a commit, paginating through GitHub's endpoint.
@@ -818,7 +1154,7 @@ class StamphogGitHubClient:
PATCH their comment; candidates are filtered to this App's bot identity (see
_is_own_sticky_comment) so an impostor comment is ignored and a fresh one is posted instead.
"""
- expected_login = _expected_sticky_comment_login()
+ expected_login = expected_app_bot_login()
for page in range(1, _MAX_PAGES + 1):
response = self._request(
"GET",
diff --git a/products/stamphog/backend/logic/reviewer.py b/products/stamphog/backend/logic/reviewer.py
index 031fc526af1c..cdf564b6083a 100644
--- a/products/stamphog/backend/logic/reviewer.py
+++ b/products/stamphog/backend/logic/reviewer.py
@@ -89,6 +89,7 @@ def build_reviewer_invocation(
files: list[dict],
reviews: list[dict],
discussion: list[dict],
+ review_threads: list[dict],
check_runs: list[dict],
pr_reactions: list[dict],
author_pr_numbers: list[int],
@@ -102,9 +103,12 @@ def build_reviewer_invocation(
``pr`` is the raw GitHub PR object (get_pr), ``files`` the raw changed-files
payload (get_pr_files) — both passed through unchanged so the engine can build
- its own PRData. ``author_pr_numbers`` are the author's merged-PR numbers the
- server fetched (the engine needs them for the git-blame familiarity signal,
- which it otherwise gets from a `gh` call it can't make in the sandbox).
+ its own PRData. ``review_threads`` are the PR's inline review threads (a
+ GraphQL-only surface the tokenless sandbox can't fetch itself), so an
+ unresolved inline "do not merge" reaches the reviewer prompt.
+ ``author_pr_numbers`` are the author's merged-PR numbers the server fetched
+ (the engine needs them for the git-blame familiarity signal, which it
+ otherwise gets from a `gh` call it can't make in the sandbox).
"""
context = {
"repo": repo,
@@ -114,6 +118,7 @@ def build_reviewer_invocation(
"files": files,
"reviews": reviews,
"discussion": discussion,
+ "review_threads": review_threads,
"check_runs": check_runs,
"pr_reactions": pr_reactions,
"author_pr_numbers": list(author_pr_numbers),
diff --git a/products/stamphog/backend/presentation/serializers.py b/products/stamphog/backend/presentation/serializers.py
index 3f35705b50d7..9e166798f6b9 100644
--- a/products/stamphog/backend/presentation/serializers.py
+++ b/products/stamphog/backend/presentation/serializers.py
@@ -133,21 +133,40 @@ class StamphogInstallInfoSerializer(serializers.Serializer):
read_only=True,
help_text=(
"GitHub install URL (github.com/apps/<slug>/installations/new) the user opens to install the "
- "App, or blank if the App slug is unconfigured."
+ "App, or blank if the App slug is unconfigured. Used for the genuinely-not-installed case; the "
+ "primary 'Connect' button uses authorize_url instead."
+ ),
+ )
+ authorize_url = serializers.CharField(
+ read_only=True,
+ help_text=(
+ "GitHub authorize URL (github.com/login/oauth/authorize) the 'Connect' button opens. "
+ "Authorize-first: an already-installed user is redirected straight back with an OAuth code (no "
+ "installation_id), and sync_installation then discovers their installations server-side. Blank "
+ "if the App client id is unconfigured."
),
)
class StamphogSyncInstallationRequestSerializer(serializers.Serializer):
- """Request body for binding a completed GitHub App installation to the current team.
+ """Request body for binding a GitHub App installation to the current team.
- Requires both the ``installation_id`` and the user-to-server OAuth ``code`` from the post-install
- redirect: the code proves the caller actually owns the installation, without which any caller could
- bind another org's installation to their own team.
+ Always requires the user-to-server OAuth ``code`` (the ownership proof) and the ``state`` token.
+ ``installation_id`` is optional: when present (the fresh-install redirect) exactly that installation
+ is verified and synced; when absent or blank (the authorize-first redirect) the caller's accessible
+ installations are discovered server-side from the code, so the client never has to supply a
+ forgeable id.
"""
installation_id = serializers.CharField(
- help_text="GitHub App installation ID returned on the post-install Setup URL redirect.",
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text=(
+ "GitHub App installation ID from the fresh-install Setup URL redirect. Optional: absent or "
+ "blank means discover the caller's installations from the OAuth code instead (authorize-first "
+ "flow). The id is not trusted on its own — ownership is always proven via the code."
+ ),
)
code = serializers.CharField(
help_text=(
@@ -165,6 +184,15 @@ class StamphogSyncInstallationRequestSerializer(serializers.Serializer):
)
+class StamphogDiscoveredInstallationSerializer(serializers.Serializer):
+ """One installation of the App the authorizing user can reach, offered for an explicit pick."""
+
+ id = serializers.CharField(read_only=True, help_text="GitHub installation id, as a string.")
+ account_login = serializers.CharField(
+ read_only=True, help_text="Login of the org or user account the installation lives on."
+ )
+
+
class StamphogSyncInstallationResponseSerializer(serializers.Serializer):
"""Result of syncing an installation: rows created/kept for this team, plus conflicting repos skipped."""
@@ -178,6 +206,24 @@ class StamphogSyncInstallationResponseSerializer(serializers.Serializer):
read_only=True,
help_text="Repository full names skipped because another team already owns them under this installation.",
)
+ app_not_installed = serializers.BooleanField(
+ read_only=True,
+ help_text=(
+ "True only on the discovery path (no installation_id) when the caller can reach no installation "
+ "of this App — it isn't installed anywhere they can see. The frontend should route the user to "
+ "the GitHub install page (install_url). Always false on the explicit installation_id path."
+ ),
+ )
+ installations = StamphogDiscoveredInstallationSerializer(
+ many=True,
+ read_only=True,
+ help_text=(
+ "Populated only on the discovery path when the caller can reach MORE than one installation of "
+ "this App: nothing was bound, and the user must pick which installation to connect. The "
+ "frontend re-runs the authorize flow and calls back with the chosen installation_id, which the "
+ "explicit path verifies. Empty whenever a bind happened (or nothing was found)."
+ ),
+ )
@extend_schema_serializer(component_name="StamphogPullRequest")
@@ -344,6 +390,17 @@ class ReviewRunSerializer(serializers.ModelSerializer):
class DigestChannelSerializer(serializers.ModelSerializer):
+ def get_fields(self) -> dict[str, serializers.Field]:
+ fields = super().get_fields()
+ # audience_key is the bucket this channel is bound to. Editing it on an existing row re-points
+ # the channel at a different audience — and can effectively re-open an audience a human opted out
+ # of, since the disabled tombstone row keying off the old audience_key would no longer match.
+ # Create-only, same pattern as the repo config's provider/repository identity fields.
+ # self.instance is set only for updates (schema generation and creates leave it None).
+ if self.instance is not None:
+ fields["audience_key"].read_only = True
+ return fields
+
resolution_source = serializers.ChoiceField(
choices=[(s.value, s.name) for s in ChannelResolutionSource],
read_only=True,
@@ -372,7 +429,12 @@ class DigestChannelSerializer(serializers.ModelSerializer):
]
read_only_fields = ["id", "last_digest_at", "created_at", "updated_at"]
extra_kwargs = {
- "audience_key": {"help_text": "Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'."},
+ "audience_key": {
+ "help_text": (
+ "Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'. Immutable "
+ "after creation — it anchors the audience and its opt-out tombstone."
+ )
+ },
"slack_integration_id": {
"help_text": "ID of the team's Slack integration used to post the digest.",
},
diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.py
index a7256c103867..e6d50980c89c 100644
--- a/products/stamphog/backend/presentation/views.py
+++ b/products/stamphog/backend/presentation/views.py
@@ -38,6 +38,7 @@ from ..logic.github_client import (
StamphogGitHubError,
exchange_oauth_code_for_user_token,
list_user_accessible_repositories,
+ list_user_installations,
user_can_access_installation,
)
from ..models import DigestChannel, DigestRun, PullRequest, ReviewRun, StamphogRepoConfig
@@ -260,13 +261,73 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.ModelViewSe
# current team. Without it, an attacker could send a logged-in member a callback carrying the
# attacker's own installation and bind it to the victim's team.
slug = settings.STAMPHOG_GITHUB_APP_SLUG
+ client_id = settings.STAMPHOG_GITHUB_APP_CLIENT_ID
install_url = ""
+ authorize_url = ""
+ # One state token backs both URLs — either callback (install Setup URL or authorize Callback URL)
+ # round-trips it, and sync_installation binds the result to the team+user encoded here.
+ state = signing.dumps({"team_id": self.team_id, "user_id": request.user.pk}, salt=_INSTALL_STATE_SALT)
if slug:
- state = signing.dumps({"team_id": self.team_id, "user_id": request.user.pk}, salt=_INSTALL_STATE_SALT)
install_url = f"https://github.com/apps/{slug}/installations/new?state={quote(state)}"
- data = StamphogInstallInfoSerializer({"app_slug": slug, "install_url": install_url}).data
+ if client_id:
+ # Authorize-first: an already-installed user gets a silent instant redirect back with an OAuth
+ # code but no installation_id, so the connect button never dead-ends on GitHub's "update
+ # installation" screen. Discovery then finds the installations from the code, server-side.
+ authorize_url = (
+ f"https://github.com/login/oauth/authorize?client_id={quote(client_id)}&state={quote(state)}"
+ )
+ data = StamphogInstallInfoSerializer(
+ {"app_slug": slug, "install_url": install_url, "authorize_url": authorize_url}
+ ).data
return Response(data)
+ def _sync_installation_repositories(
+ self, installation_id: str, user_token: str
+ ) -> tuple[list[StamphogRepoConfig], list[str]]:
+ """Bind every user-accessible repo in one installation to the current team. Returns (synced, skipped).
+
+ Enumerate with the USER token, not the app installation token: bind only the repos this user can
+ actually reach in the installation, so proving access to one repo can't attach repos they can't
+ see. The app-token list would return every repo the installer selected regardless of this user.
+ Raises :class:`StamphogGitHubError` on an enumeration failure so the caller fails closed. Shared by
+ the explicit-id and discovery paths so both bind identically.
+ """
+ repositories = list_user_accessible_repositories(installation_id, user_token)
+ synced: list[StamphogRepoConfig] = []
+ skipped: list[str] = []
+ # Bind the per-row savepoint to the model's routed DB (stamphog_db_writer when the product DB is
+ # configured, else default) — a bare atomic() opens on the default connection, so the get_or_create
+ # would run outside any transaction on the product DB.
+ write_db = router.db_for_write(StamphogRepoConfig)
+ for full_name in repositories:
+ # Per-row savepoint: an IntegrityError only rolls back that row, leaving the rest of the
+ # batch (and the outer autocommit context) intact.
+ try:
+ with transaction.atomic(using=write_db):
+ config, _ = StamphogRepoConfig.objects.for_team(self.team_id).get_or_create(
+ provider="github",
+ installation_id=installation_id,
+ repository=full_name,
+ # for_team() scopes the read but not row creation, so team_id is explicit here.
+ # Bind disabled: an installation can surface hundreds of repos, so connect them
+ # but don't start reviewing until a human toggles each on. enabled only seeds new
+ # rows; an existing row's toggle is never flipped.
+ defaults={"team_id": self.team_id, "enabled": False},
+ )
+ except IntegrityError:
+ # The unique (team, repository) constraint tripped: a same-team row for this repo already
+ # exists under a different installation_id — the manually-created config (blank
+ # installation) finally being bound. Adopt it instead of skipping; only a real conflict
+ # (already bound to another installation) stays skipped.
+ adopted = _adopt_preexisting_config(self.team_id, full_name, installation_id)
+ if adopted is None:
+ skipped.append(full_name)
+ else:
+ synced.append(adopted)
+ continue
+ synced.append(config)
+ return synced, skipped
+
@extend_schema(
request=StamphogSyncInstallationRequestSerializer,
responses={200: StamphogSyncInstallationResponseSerializer},
@@ -276,10 +337,16 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.ModelViewSe
# Custom action names fall outside the default read/write action classification, so without
# explicit required_scopes this write would be reachable with no scope check at all.
#
- # Post-install binding: GitHub redirects the browser back with an installation_id AND a
- # user-to-server OAuth code. We verify the code proves the caller owns the installation before
- # registering a StamphogRepoConfig for every repo it covers under the CURRENT team. Without the
- # ownership check any caller could bind another org's installation and hijack its webhooks. A repo
+ # Post-authorize binding. GitHub redirects the browser back with a user-to-server OAuth code and
+ # our state token; installation_id is present only on the fresh-install redirect, absent on the
+ # authorize-first redirect. We exchange the code for the user's token (the ownership proof) and:
+ # - explicit installation_id → verify the user can reach exactly it, then sync it.
+ # - no installation_id → discover the user's installations of THIS App from the token. Exactly
+ # one → sync it (the overwhelmingly common case). Several → bind NOTHING and return them as
+ # choices: reachability is not intent, and binding foreign orgs' installations here would
+ # misroute their webhooks (oldest-wins resolution). Zero isn't an error — the App isn't
+ # installed anywhere the user can see, signalled via app_not_installed.
+ # Either way ownership is proven by the code, never the caller-supplied (forgeable) id. A repo
# already owned by another team is skipped, not fatal, so one shared repo can't block the batch.
request_serializer = StamphogSyncInstallationRequestSerializer(data=request.data)
request_serializer.is_valid(raise_exception=True)
@@ -315,73 +382,77 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.ModelViewSe
raise PermissionDenied("This installation link was started by a different user.")
# Fail closed: no proven ownership, no binding. A missing OAuth token (bad/expired code or unset
- # Stamphog OAuth creds) is a 400; a valid user who simply can't reach the installation is a 403.
+ # Stamphog OAuth creds) is a 400; a valid user who simply can't reach an installation is a 403.
user_token = exchange_oauth_code_for_user_token(code)
if user_token is None:
raise ValidationError({"code": "Could not verify GitHub authorization. Reinstall the app and try again."})
- try:
- owns_installation = user_can_access_installation(installation_id, user_token)
- except StamphogGitHubError:
- logger.warning(
- "stamphog sync_installation: installation ownership check failed",
- installation_id=installation_id,
- team_id=self.team_id,
- )
- raise ValidationError({"installation_id": "Failed to verify installation access. Try again."})
- if not owns_installation:
- logger.warning(
- "stamphog sync_installation: caller does not own installation",
- installation_id=installation_id,
- team_id=self.team_id,
- )
- raise PermissionDenied("You do not have access to this GitHub App installation.")
- # Enumerate with the USER token, not the app installation token: bind only the repos this user can
- # actually reach in the installation, so proving access to one repo can't attach repos they can't
- # see. The app-token list would return every repo the installer selected regardless of this user.
- try:
- repositories = list_user_accessible_repositories(installation_id, user_token)
- except StamphogGitHubError:
- logger.warning(
- "stamphog sync_installation: listing user-accessible repositories failed",
- installation_id=installation_id,
- team_id=self.team_id,
- )
- raise ValidationError({"installation_id": "Failed to list accessible repositories. Try again."})
+ if installation_id:
+ # Explicit-id path (fresh-install redirect): the id is caller-supplied, so verify the user can
+ # actually reach exactly it before binding — otherwise a caller who learns another org's
+ # installation_id could bind its repos and hijack its webhooks.
+ try:
+ owns_installation = user_can_access_installation(installation_id, user_token)
+ except StamphogGitHubError:
+ logger.warning(
+ "stamphog sync_installation: installation ownership check failed",
+ installation_id=installation_id,
+ team_id=self.team_id,
+ )
+ raise ValidationError({"installation_id": "Failed to verify installation access. Try again."})
+ if not owns_installation:
+ logger.warning(
+ "stamphog sync_installation: caller does not own installation",
+ installation_id=installation_id,
+ team_id=self.team_id,
+ )
+ raise PermissionDenied("You do not have access to this GitHub App installation.")
+ installation_ids = [installation_id]
+ else:
+ # Discovery path (authorize-first redirect): GitHub returns only installations of THIS App the
+ # user can reach, so the list is itself the ownership proof — no per-id verification needed.
+ try:
+ discovered = list_user_installations(user_token)
+ except StamphogGitHubError:
+ logger.warning(
+ "stamphog sync_installation: discovering user installations failed", team_id=self.team_id
+ )
+ raise ValidationError({"code": "Failed to discover GitHub App installations. Try again."})
+ if not discovered:
+ # The App isn't installed anywhere the user can see. Not an error: the frontend routes them
+ # to the GitHub install page (install_url) off app_not_installed.
+ data = StamphogSyncInstallationResponseSerializer(
+ {"synced": [], "skipped": [], "app_not_installed": True, "installations": []}
+ ).data
+ return Response(data)
+ if len(discovered) > 1:
+ # Reachability is not intent: a user in several orgs that all carry the App must pick which
+ # installation this team binds — silently binding them all would attach foreign orgs' repos
+ # here, and via the oldest-wins webhook resolution even blackhole another team's future
+ # connect. Bind nothing; the frontend re-runs the flow with an explicit installation_id
+ # (which the explicit path above verifies).
+ data = StamphogSyncInstallationResponseSerializer(
+ {"synced": [], "skipped": [], "app_not_installed": False, "installations": discovered}
+ ).data
+ return Response(data)
+ installation_ids = [discovered[0]["id"]]
synced: list[StamphogRepoConfig] = []
skipped: list[str] = []
- # Bind the per-row savepoint to the model's routed DB (stamphog_db_writer when the product DB is
- # configured, else default) — a bare atomic() opens on the default connection, so the get_or_create
- # would run outside any transaction on the product DB.
- write_db = router.db_for_write(StamphogRepoConfig)
- for full_name in repositories:
- # Per-row savepoint: an IntegrityError only rolls back that row, leaving the rest of the
- # batch (and the outer autocommit context) intact.
+ for one_installation_id in installation_ids:
try:
- with transaction.atomic(using=write_db):
- config, _ = StamphogRepoConfig.objects.for_team(self.team_id).get_or_create(
- provider="github",
- installation_id=installation_id,
- repository=full_name,
- # for_team() scopes the read but not row creation, so team_id is explicit here.
- # Bind disabled: an installation can surface hundreds of repos, so connect them
- # but don't start reviewing until a human toggles each on. enabled only seeds new
- # rows; an existing row's toggle is never flipped.
- defaults={"team_id": self.team_id, "enabled": False},
- )
- except IntegrityError:
- # The unique (team, repository) constraint tripped: a same-team row for this repo already
- # exists under a different installation_id — the manually-created config (blank
- # installation) finally being bound. Adopt it instead of skipping; only a real conflict
- # (already bound to another installation) stays skipped.
- adopted = _adopt_preexisting_config(self.team_id, full_name, installation_id)
- if adopted is None:
- skipped.append(full_name)
- else:
- synced.append(adopted)
- continue
- synced.append(config)
+ installation_synced, installation_skipped = self._sync_installation_repositories(
+ one_installation_id, user_token
+ )
+ except StamphogGitHubError:
+ logger.warning(
+ "stamphog sync_installation: listing user-accessible repositories failed",
+ installation_id=one_installation_id,
+ team_id=self.team_id,
+ )
+ raise ValidationError({"installation_id": "Failed to list accessible repositories. Try again."})
+ synced.extend(installation_synced)
+ skipped.extend(installation_skipped)
# Every synced row records the caller as its connecting user — the identity the review
# sandbox's short-lived gateway token is minted under. Re-syncs re-stamp on purpose: the
@@ -393,8 +464,10 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.ModelViewSe
connected_by_user_id=request.user.pk, updated_at=timezone.now()
)
- response = StamphogSyncInstallationResponseSerializer({"synced": synced, "skipped": skipped})
- return Response(response.data)
+ data = StamphogSyncInstallationResponseSerializer(
+ {"synced": synced, "skipped": skipped, "app_not_installed": False, "installations": []}
+ ).data
+ return Response(data)
class ReviewRunViewSet(_StamphogTeamScopedViewSet, viewsets.ReadOnlyModelViewSet):
diff --git a/products/stamphog/backend/presentation/webhooks.py b/products/stamphog/backend/presentation/webhooks.py
index a1310bab530d..97b2aa2b2475 100644
--- a/products/stamphog/backend/presentation/webhooks.py
+++ b/products/stamphog/backend/presentation/webhooks.py
@@ -38,7 +38,7 @@ def stamphog_github_webhook(request: HttpRequest) -> HttpResponse:
if request.method != "POST":
return HttpResponse(status=405)
- secret = getattr(settings, "STAMPHOG_GITHUB_WEBHOOK_SECRET", "")
+ secret = getattr(settings, "STAMPHOG_GITHUB_APP_WEBHOOK_SECRET", "")
if not secret:
logger.error("stamphog_webhook_not_configured")
return HttpResponse("Webhook not configured", status=500)
diff --git a/products/stamphog/backend/tasks/digest.py b/products/stamphog/backend/tasks/digest.py
index 5b8312bca78c..6fdf161a94ce 100644
--- a/products/stamphog/backend/tasks/digest.py
+++ b/products/stamphog/backend/tasks/digest.py
@@ -10,9 +10,10 @@ the PRs to the run. A Slack failure leaves the PRs unlinked so the next day retr
from __future__ import annotations
+import time
from datetime import datetime, timedelta
-from django.db import router, transaction
+from django.db import InterfaceError, OperationalError, router, transaction
from django.utils import timezone
import structlog
@@ -40,6 +41,11 @@ DIGEST_MAX_PRS_PER_RUN = 100
# failing) — reclaim it so those PRs re-enter the next digest instead of being stranded forever.
STALE_PENDING_RUN_MINUTES = 60
+# The proof-of-post write is the dedup proof (see send_digest_for_channel); a transient DB blip there
+# converts a Slack-accepted digest into a duplicate re-send, so retry the write a few times first.
+_PROOF_OF_POST_WRITE_ATTEMPTS = 3
+_PROOF_OF_POST_WRITE_RETRY_SECONDS = 0.2
+
def _previous_run_slot(now: datetime) -> datetime:
"""The weekday 07:00 UTC digest slot before the current one.
@@ -144,11 +150,23 @@ def send_digest_for_channel(digest_channel_id: str, team_id: int) -> None:
# write below. If the worker dies in between, the reclaim sweeper sees a non-empty slack_message_ts,
# knows this run already posted, and finalizes it instead of unlinking + re-sending its PRs to Slack.
# The metadata rides along so a reclaim-finalized run keeps its real pr_count/summary, not zeros.
- DigestRun.objects.for_team(team_id).filter(id=run.id).update(
- slack_message_ts=message_ts or "posted",
- pr_count=len(prs),
- summary=summary.to_dict(),
- )
+ # This single write is the only thing standing between a Slack-accepted message and a duplicate
+ # re-send, so a transient DB blip here (not a Slack failure) must not be taken at face value: retry
+ # it a few times before letting the exception propagate.
+ for attempt in range(_PROOF_OF_POST_WRITE_ATTEMPTS):
+ try:
+ DigestRun.objects.for_team(team_id).filter(id=run.id).update(
+ slack_message_ts=message_ts or "posted",
+ pr_count=len(prs),
+ summary=summary.to_dict(),
+ )
+ break
+ except (OperationalError, InterfaceError):
+ # Only the transient connectivity classes: retrying an IntegrityError/ProgrammingError
+ # burns the attempts on a deterministic failure and delays the real traceback.
+ if attempt == _PROOF_OF_POST_WRITE_ATTEMPTS - 1:
+ raise
+ time.sleep(_PROOF_OF_POST_WRITE_RETRY_SECONDS)
now = timezone.now()
with transaction.atomic(using=write_db):
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index a452fc22b432..55a14a98adae 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -41,7 +41,7 @@ from posthog.temporal.oauth import create_oauth_access_token_for_user
from products.stamphog.backend.facade.enums import TERMINAL_STATUSES, ReviewMode, ReviewRunStatus, ReviewVerdict
from products.stamphog.backend.logic.approvals import dismiss_stale_approvals_for_head
from products.stamphog.backend.logic.audiences import resolve_audience_key
-from products.stamphog.backend.logic.github_client import StamphogGitHubClient
+from products.stamphog.backend.logic.github_client import StamphogGitHubClient, expected_app_bot_login
from products.stamphog.backend.logic.reviewer import (
ReviewerInvocation,
ReviewerVerdict,
@@ -221,6 +221,9 @@ def fetch_review_context(input: StamphogReviewInput) -> dict:
reviews = client.get_pr_reviews(repo, pull_request.pr_number)
# Top-level discussion comments are blocker context (a maintainer's "please hold").
discussion = client.get_pr_discussion(repo, pull_request.pr_number)
+ # Inline review threads (GraphQL-only) carry a maintainer's unresolved "do not merge" that the
+ # top-level discussion misses; fails closed on truncation/errors, same as get_pr_discussion.
+ review_threads = client.get_pr_review_threads(repo, pull_request.pr_number)
# Head-commit check runs let the engine's migration gate see a passing "Migration risk" check.
check_runs = client.get_check_runs(repo, run.head_sha)
@@ -239,6 +242,7 @@ def fetch_review_context(input: StamphogReviewInput) -> dict:
"files": files,
"reviews": reviews,
"discussion": discussion,
+ "review_threads": review_threads,
"check_runs": check_runs,
"pr_reactions": client.get_pr_reactions(repo, pull_request.pr_number),
"policy_files": policy_files,
@@ -275,16 +279,50 @@ def dismiss_stale_approvals(input: StamphogReviewInput) -> dict:
# pending — if it refuses, an earlier same-head approval must not keep the PR mergeable. The
# sweep's same-head exclusion remains for the skip paths, where no new review will run and the
# current-head approval is still the delivered verdict.
- dismissed = dismiss_stale_approvals_for_head(
- input.team_id,
- pull_request,
- repo_config,
- "",
- message="A new stamphog review started for this PR — the fresh verdict replaces this approval.",
+ message = "A new stamphog review started for this PR — the fresh verdict replaces this approval."
+ dismissed = dismiss_stale_approvals_for_head(input.team_id, pull_request, repo_config, "", message=message)
+
+ # Belt-and-braces GitHub-side sweep (see _sweep_own_github_approvals): the DB sweep above keys off
+ # posted_review_id, so an approval this App left on GitHub with NO ReviewRun row carrying its id (a run
+ # that approved but crashed before persisting, or any other drift) is invisible to it and would stand
+ # forever. keep_review_ids=frozenset() voids everything, regardless of head — the same all-heads
+ # semantic the DB sweep uses at workflow start.
+ client = StamphogGitHubClient(repo_config.installation_id)
+ github_dismissed = _sweep_own_github_approvals(
+ client, repo_config, pull_request, message, keep_review_ids=frozenset()
)
- activity.logger.info(f"Dismissed {dismissed} stale approval(s) for run {run.id} (pr #{pull_request.pr_number})")
- return {"dismissed": dismissed}
+ activity.logger.info(
+ f"Dismissed {dismissed} DB-tracked + {github_dismissed} GitHub-side stale approval(s) "
+ f"for run {run.id} (pr #{pull_request.pr_number})"
+ )
+ return {"dismissed": dismissed, "github_dismissed": github_dismissed}
+
+
+@asyncify
+def signal_review_started(input: StamphogReviewInput) -> dict:
+ """Post stamphog's own 👀 on the PR the moment this run commits to reviewing.
+
+ Mirrors the convention this same workflow reads off OTHER bots (``STAMPHOG_TRUSTED_REACTOR_BOTS``,
+ ``list_in_flight_reviewer_bots``): a fresh 👀 means "a review is in flight". Emitting it lets other
+ tooling (and a human watching the PR) see stamphog is actively working, the same signal every other
+ reviewer bot already gives. Runs right after ``dismiss_stale_approvals`` — the moment this run
+ commits to reviewing — so the 👀 appears before the (possibly long) context fetch and sandbox run.
+ Cosmetic only: ``add_pr_reaction`` fails open (see its docstring), so a reaction hiccup here never
+ fails or retries this activity, let alone the review itself. The returned reaction id (if any) rides
+ on ``run.output`` so the terminal activities (``post_verdict``, ``mark_review_failed``) can remove it.
+ """
+ run = _load_run(input)
+ if run.status == ReviewRunStatus.SUPERSEDED:
+ return {"reaction_id": None}
+ pull_request = run.pull_request
+ repo_config = pull_request.repo_config
+ client = StamphogGitHubClient(repo_config.installation_id)
+ reaction_id = client.add_pr_reaction(repo_config.repository, pull_request.pr_number)
+ run.output = {**(run.output or {}), "own_eyes_reaction_id": reaction_id}
+ run.save(update_fields=["output", "updated_at"])
+ return {"reaction_id": reaction_id}
@activity.defn
@@ -308,12 +346,18 @@ def list_in_flight_reviewer_bots(input: StamphogReviewInput) -> dict:
run.save(update_fields=["output", "updated_at"])
now = timezone.now()
+ # Exclude stamphog's own bot login: STAMPHOG_TRUSTED_REACTOR_BOTS is a hardcoded set of OTHER
+ # reviewer bots' logins, so this app's own 👀 (posted by signal_review_started) can't collide
+ # with it today — but that set is just literal strings, not a same-app check, so a future
+ # addition or a misconfigured STAMPHOG_GITHUB_APP_SLUG could make stamphog wait out itself.
+ own_login = (expected_app_bot_login() or "").lower()
in_flight = sorted(
{
reaction["user"]
for reaction in reactions
if reaction.get("content") == "eyes"
- and (reaction.get("user") or "").lower() in STAMPHOG_TRUSTED_REACTOR_BOTS
+ and (login := (reaction.get("user") or "").lower()) in STAMPHOG_TRUSTED_REACTOR_BOTS
+ and login != own_login
and (created := parse_datetime(reaction.get("created_at") or "")) is not None
and (now - created).total_seconds() <= STAMPHOG_BOT_EYES_MAX_AGE_SECONDS
}
@@ -344,6 +388,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
files = output.get("files", [])
reviews = output.get("reviews", [])
discussion = output.get("discussion", [])
+ review_threads = output.get("review_threads", [])
check_runs = output.get("check_runs", [])
pr_reactions = output.get("pr_reactions", [])
policy_files = output.get("policy_files", {})
@@ -384,6 +429,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
files=files,
reviews=reviews,
discussion=discussion,
+ review_threads=review_threads,
check_runs=check_runs,
pr_reactions=pr_reactions,
author_pr_numbers=author_pr_numbers,
@@ -442,6 +488,93 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
return {"exit_code": result.exit_code}
+def _sweep_own_github_approvals(
+ client: StamphogGitHubClient,
+ repo_config: StamphogRepoConfig,
+ pull_request: PullRequest,
+ message: str,
+ *,
+ keep_review_ids: frozenset[int],
+) -> int:
+ """Dismiss every one of this App's still-active APPROVE reviews on the PR, except ``keep_review_ids``.
+
+ Asks GitHub for our own still-active approvals and retracts each one regardless of head — the DB sweep
+ keys off ``posted_review_id``, so an approval this App left on GitHub with no ReviewRun row carrying its
+ id is invisible to it. Identity fails closed without a configured app slug (``list_own_active_approvals``
+ returns nothing), and ``dismiss_pr_review`` swallows 422, so re-dismissing an already-retracted review is
+ an idempotent no-op. Returns the count dismissed.
+
+ ``keep_review_ids`` spares specific reviews: the terminal-sweep caller passes the persisted approval ids
+ of OTHER live runs so a slow run at its own terminal never dismisses a newer run's legit approval.
+ ``dismiss_stale_approvals`` passes an empty set — at workflow start every standing approval goes.
+ """
+ dismissed = 0
+ for review in client.list_own_active_approvals(repo_config.repository, pull_request.pr_number):
+ review_id = _comment_id(review)
+ if review_id is None or review_id in keep_review_ids:
+ continue
+ client.dismiss_pr_review(repo_config.repository, pull_request.pr_number, review_id, message)
+ dismissed += 1
+ return dismissed
+
+
+def _peer_persisted_approval_ids(team_id: int, pull_request: PullRequest, run: ReviewRun) -> frozenset[int]:
+ """Persisted approval ids of OTHER live runs on this PR — the terminal sweep's allow-list.
+
+ A run reaching a non-approve terminal re-runs the GitHub-side own-approvals sweep to catch an orphan an
+ older, superseded run posted after this (newer) run's startup sweep already ran. But it must never
+ dismiss a NEWER run's legitimately posted approval, so keep every ``posted_review_id`` on a run for this
+ PR that still holds a live status (not superseded, not failed) — those approvals stand on purpose.
+
+ Writer-pinned: this read gates a GitHub write, and a lagged replica could miss a newer run's freshly
+ persisted approval and dismiss it (see CLAUDE.md reader-lag invariant).
+ """
+ peer_ids = (
+ ReviewRun.objects.for_team(team_id)
+ .using(router.db_for_write(ReviewRun))
+ .filter(pull_request=pull_request, posted_review_id__isnull=False)
+ .exclude(id=run.id)
+ .exclude(status__in=(ReviewRunStatus.SUPERSEDED, ReviewRunStatus.FAILED))
+ .values_list("posted_review_id", flat=True)
+ )
+ return frozenset(review_id for review_id in peer_ids if review_id is not None)
+
+
+_TERMINAL_SWEEP_MESSAGE = (
+ "This stamphog run finished without approving — retracting an approval an earlier run left standing so "
+ "it can't satisfy required reviews over a verdict that no longer approves."
+)
+
+
+def _sweep_orphan_approvals_at_terminal(client: StamphogGitHubClient, run: ReviewRun, team_id: int) -> None:
+ """Re-run the GitHub-side own-approvals sweep when a run ends WITHOUT a standing approval of its own.
+
+ Closes the supersession orphan race: an older run can clear post_verdict's final guards, get superseded,
+ then land its GitHub approval AFTER the newer run's startup sweep already ran. If the newer run's verdict
+ is non-APPROVE (or the run fails), nothing lists our own approvals again, so the orphan satisfies branch
+ protection over a refusing verdict until some future run sweeps. Running the sweep at this run's own
+ terminal catches it — the run that superseded the orphan-poster is the natural place to clean up.
+
+ ``keep_review_ids`` spares every OTHER live run's persisted approval, so a slow run at terminal can't
+ dismiss a newer run's legit approval. UNLIKE the fail-closed STARTUP sweep, this one must not fail or
+ retry the terminal transition if GitHub errors: the terminal save has to win, and the approval-integrity
+ gap on error here is the pre-existing exposure, strictly no worse than before this sweep existed.
+ """
+ keep_review_ids = _peer_persisted_approval_ids(team_id, run.pull_request, run)
+ try:
+ _sweep_own_github_approvals(
+ client,
+ run.pull_request.repo_config,
+ run.pull_request,
+ _TERMINAL_SWEEP_MESSAGE,
+ keep_review_ids=keep_review_ids,
+ )
+ except Exception:
+ activity.logger.exception(
+ f"Run {run.id}: terminal orphan-approval sweep failed; leaving the pre-existing exposure as-is"
+ )
+
+
def _dismiss_orphaned_approval(client: StamphogGitHubClient, run: ReviewRun, team_id: int) -> None:
"""Retract an approval this run posted to GitHub but never recorded as its saved verdict.
@@ -468,6 +601,40 @@ def _dismiss_orphaned_approval(client: StamphogGitHubClient, run: ReviewRun, tea
activity.logger.info(f"Run {run.id}: dismissed orphaned approval {run.posted_review_id}")
+def _remove_own_eyes_reaction(client: StamphogGitHubClient, run: ReviewRun) -> None:
+ """Remove this run's own "review in flight" 👀, if ``signal_review_started`` posted one.
+
+ Called from the terminal activities (``post_verdict``'s completion path, ``mark_review_failed``)
+ once this run is done actively reviewing — AFTER this run's terminal save, so the peer check
+ below counts only genuinely-other live runs. No id on ``run.output`` means either the signal
+ never posted one (fail-open there too) or a later run already adopted/removed it — either way,
+ nothing to do. ``remove_pr_reaction`` itself fails open, so this never raises into the caller.
+
+ GitHub keeps ONE 👀 per (user, content) per issue, so overlapping runs share the same reaction
+ id: a run created after this one went terminal (a fresh delivery, not a supersession) adopts the
+ identical id in its own ``signal_review_started``. Removing it here would strip the in-flight
+ signal out from under that still-reviewing peer, so skip when a live peer exists — the last
+ standing run removes. Writer-pinned: a lagged replica missing the just-created peer would remove
+ under it (reader-lag invariant).
+ """
+ reaction_id = (run.output or {}).get("own_eyes_reaction_id")
+ if not isinstance(reaction_id, int):
+ return
+ pull_request = run.pull_request
+ live_peer_exists = (
+ ReviewRun.objects.for_team(run.team_id)
+ .using(router.db_for_write(ReviewRun))
+ .filter(pull_request=pull_request)
+ .exclude(id=run.id)
+ .exclude(status__in=TERMINAL_STATUSES)
+ .exists()
+ )
+ if live_peer_exists:
+ activity.logger.info(f"Run {run.id}: leaving the shared in-flight reaction for a live peer run")
+ return
+ client.remove_pr_reaction(pull_request.repo_config.repository, pull_request.pr_number, reaction_id)
+
+
@activity.defn
@asyncify
def post_verdict(input: StamphogReviewInput) -> dict:
@@ -546,12 +713,30 @@ def post_verdict(input: StamphogReviewInput) -> dict:
# Idempotent under Temporal at-least-once retries: the id is persisted the moment GitHub
# accepts the review, so a retry after any later crash skips re-approving.
if run.posted_review_id is None:
- body = _neutralize_active_markdown(_scrub_credentials(parsed.review_body or _approve_comment(parsed)))
- review = client.post_approve_review(repo, pull_request.pr_number, body, run.head_sha)
- run.posted_review_id = _comment_id(review)
+ # Adopt-before-post: a prior attempt could have posted the approval to GitHub, then crashed
+ # BEFORE the immediate-persist below — leaving an approval with no DB trace that the
+ # posted_review_id-keyed sweep can never see. Re-posting would stack a SECOND standing
+ # approval. So first ask GitHub whether we already have an active APPROVE pinned to exactly
+ # this head; adopt its id instead of posting again if so. Identity fails closed without a
+ # configured app slug (list_own_active_approvals returns nothing), so we never adopt another
+ # bot's review off a fuzzy match — we post fresh, same as before.
+ adopted_review_id: int | None = None
+ for review in client.list_own_active_approvals(repo, pull_request.pr_number):
+ if (review.get("commit_id") or "") != run.head_sha:
+ continue
+ adopted_review_id = _comment_id(review)
+ if adopted_review_id is not None:
+ break
+ if adopted_review_id is not None:
+ run.posted_review_id = adopted_review_id
+ else:
+ body = _neutralize_active_markdown(_scrub_credentials(parsed.review_body or _approve_comment(parsed)))
+ review = client.post_approve_review(repo, pull_request.pr_number, body, run.head_sha)
+ run.posted_review_id = _comment_id(review)
# Persist the id immediately, outside the conditional terminal save below: if that save
# loses to a supersession or this activity crashes, this row is the only record the
- # approval exists — the orphan-dismissal paths and the stale-approval sweep need it.
+ # approval exists — the orphan-dismissal paths and the stale-approval sweep need it. The
+ # adopted id must be persisted exactly the same way as a freshly posted one.
ReviewRun.objects.for_team(input.team_id).filter(id=run.id).update(
posted_review_id=run.posted_review_id, updated_at=timezone.now()
)
@@ -605,6 +790,15 @@ def post_verdict(input: StamphogReviewInput) -> dict:
# and unstamped, so the closed-webhook path and this path can't double-stamp.
if run.verdict == ReviewVerdict.APPROVED:
_stamp_digest_audience_if_merged(repo_config, pull_request, run, current_pr)
+ else:
+ # This run reached a terminal outcome without a standing approval of its own (gated / refused /
+ # escalate / wait). Re-run the GitHub-side sweep now to catch an orphan an older, superseded run
+ # posted after this run's startup sweep — see _sweep_orphan_approvals_at_terminal.
+ _sweep_orphan_approvals_at_terminal(client, run, input.team_id)
+
+ # The run stopped actively reviewing the moment the terminal save above committed — remove the
+ # "review in flight" 👀 now, whichever verdict landed (approved, gated, refused, escalate).
+ _remove_own_eyes_reaction(client, run)
activity.logger.info(f"Posted verdict {parsed.verdict} for run {run.id}")
return {"verdict": str(parsed.verdict)}
@@ -627,17 +821,29 @@ def mark_review_failed(input: MarkReviewFailedInput) -> None:
# would ever retract the approval on a FAILED run. Dismiss BEFORE marking FAILED: if the
# dismissal itself fails, this activity retries into a still-non-terminal run and tries again,
# whereas the reverse order would hit the terminal guard above and orphan the approval forever.
+ client = StamphogGitHubClient(run.pull_request.repo_config.installation_id)
if run.verdict != ReviewVerdict.APPROVED and run.posted_review_id and run.approval_dismissed_at is None:
- client = StamphogGitHubClient(run.pull_request.repo_config.installation_id)
_dismiss_orphaned_approval(client, run, input.team_id)
# Persist only the first line, truncated: run.error is returned by the serializer to anyone with
# stamphog:read, and raw exception text can embed repository file content (a yaml.YAMLError over
# .stamphog/policy.yml echoes the offending source lines on its continuation lines). Full detail is
# already in the worker logs — the workflow logs the complete error before calling this activity.
- run.status = ReviewRunStatus.FAILED
- run.error = first_error_line
- run.completed_at = timezone.now()
- run.save(update_fields=["status", "error", "completed_at", "updated_at"])
+ # Conditional like every terminal save (the load-time guard above can race an in-flight
+ # supersession): a run that just went SUPERSEDED keeps that status, FAILED must not clobber it.
+ now = timezone.now()
+ ReviewRun.objects.for_team(input.team_id).filter(id=run.id).exclude(status__in=TERMINAL_STATUSES).update(
+ status=ReviewRunStatus.FAILED, error=first_error_line, completed_at=now, updated_at=now
+ )
+ # This run is done reviewing (unrecoverably) — clean up its own "review in flight" 👀 too. After
+ # the terminal save on purpose: the removal's live-peer check must see this run as terminal, or
+ # two concurrently failing runs could each defer to the other and leak the reaction.
+ _remove_own_eyes_reaction(client, run)
+
+ # A newer run that FAILS leaves the same supersession-orphan exposure a non-approve post_verdict does:
+ # an older, superseded run's approval could have landed after this run's startup sweep, and a FAILED run
+ # never lists our approvals again. Sweep after the FAILED save so a GitHub hiccup can't block the
+ # terminal transition (the STARTUP sweep is fail-closed; this terminal one is fail-open on purpose).
+ _sweep_orphan_approvals_at_terminal(client, run, input.team_id)
# Hosted failures were only visible in worker logs; capture them so the dashboards see hosted
# breakage next to the review-completed events. ph_scoped_capture, not posthoganalytics.capture —
diff --git a/products/stamphog/backend/temporal/registry.py b/products/stamphog/backend/temporal/registry.py
index fd3aec75ea53..d2a433da5dd6 100644
--- a/products/stamphog/backend/temporal/registry.py
+++ b/products/stamphog/backend/temporal/registry.py
@@ -13,6 +13,7 @@ from products.stamphog.backend.temporal.activities import (
mark_review_failed,
post_verdict,
run_review_in_sandbox,
+ signal_review_started,
)
from products.stamphog.backend.temporal.workflow import StamphogReviewWorkflow
@@ -20,6 +21,7 @@ WORKFLOWS = [StamphogReviewWorkflow]
ACTIVITIES = [
dismiss_stale_approvals,
+ signal_review_started,
fetch_review_context,
list_in_flight_reviewer_bots,
run_review_in_sandbox,
diff --git a/products/stamphog/backend/temporal/workflow.py b/products/stamphog/backend/temporal/workflow.py
index 514145a17f7b..88c2550baf69 100644
--- a/products/stamphog/backend/temporal/workflow.py
+++ b/products/stamphog/backend/temporal/workflow.py
@@ -38,6 +38,7 @@ with temporalio.workflow.unsafe.imports_passed_through():
mark_review_failed,
post_verdict,
run_review_in_sandbox,
+ signal_review_started,
)
@@ -59,6 +60,18 @@ class StamphogReviewWorkflow(PostHogWorkflow):
retry_policy=ACTIVITY_RETRY_POLICY,
)
+ # New command added after this workflow's initial rollout — gated so in-flight executions
+ # replaying their recorded history (which never saw this activity) don't hit a
+ # Non-Deterministic Error. The moment this run commits to reviewing (right after the stale
+ # approval sweep) is also the moment it should show a "review in flight" 👀 on the PR.
+ if workflow.patched("stamphog-eyes-reaction"):
+ await workflow.execute_activity(
+ signal_review_started,
+ input,
+ start_to_close_timeout=POST_VERDICT_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+
await workflow.execute_activity(
fetch_review_context,
input,
diff --git a/products/stamphog/backend/tests/conftest.py b/products/stamphog/backend/tests/conftest.py
index e432ae156358..08f98e952f93 100644
--- a/products/stamphog/backend/tests/conftest.py
+++ b/products/stamphog/backend/tests/conftest.py
@@ -25,6 +25,7 @@ from products.stamphog.backend.temporal.activities import (
mark_review_failed,
post_verdict,
run_review_in_sandbox,
+ signal_review_started,
)
from products.stamphog.backend.tests import fakes
@@ -107,12 +108,14 @@ def _inline_review_workflow(review_run_id: str, team_id: int) -> None:
"""Stand in for the Temporal client by driving the real activities in order.
Mirrors StamphogReviewWorkflow: dismiss stale approvals FIRST (fail-closed — even a context-fetch
- failure must not leave an earlier head's approval standing), then fetch context, run in the (faked)
- sandbox, post the verdict; on any error mark the run failed, exactly like the workflow's failure path.
+ failure must not leave an earlier head's approval standing), signal the review has started (the
+ "review in flight" 👀), then fetch context, run in the (faked) sandbox, post the verdict; on any
+ error mark the run failed, exactly like the workflow's failure path.
"""
inp = StamphogReviewInput(review_run_id=review_run_id, team_id=team_id)
try:
_run_activity(dismiss_stale_approvals, inp)
+ _run_activity(signal_review_started, inp)
_run_activity(fetch_review_context, inp)
# One bot-wait poll, no sleeping: mirrors the workflow's loop semantics (refresh the
# reactions snapshot, then proceed) without its durable timers.
@@ -182,7 +185,7 @@ def stamphog_chain() -> Iterator[StamphogChain]:
with ExitStack() as stack:
stack.enter_context(
override_settings(
- STAMPHOG_GITHUB_WEBHOOK_SECRET=WEBHOOK_SECRET,
+ STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET,
STAMPHOG_GITHUB_APP_ID="123456",
STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key(),
)
diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.py
index 4cf8d3de451f..4f736787e3a4 100644
--- a/products/stamphog/backend/tests/fakes.py
+++ b/products/stamphog/backend/tests/fakes.py
@@ -101,6 +101,7 @@ _CONTENTS_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/contents/(?P<path>.+)$
_CHECK_RUNS_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/commits/(?P<sha>[^/]+)/check-runs$")
_COLLABORATOR_PERMISSION_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/collaborators/(?P<username>[^/]+)/permission$")
_PR_REACTIONS_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/issues/(?P<number>\d+)/reactions$")
+_PR_REACTION_DELETE_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/issues/(?P<number>\d+)/reactions/(?P<rid>\d+)$")
_API_PREFIX = "https://api.github.com"
@@ -129,6 +130,8 @@ class GitHubRecorder:
self.prs: dict[tuple[str, int], dict] = {}
self.pr_files: dict[tuple[str, int], list[dict]] = {}
self.pr_reviews: dict[tuple[str, int], list[dict]] = {}
+ # (repo, number) -> GraphQL reviewThreads node dicts for get_pr_review_threads; default none.
+ self.review_threads: dict[tuple[str, int], list[dict]] = {}
# Pre-existing issue comments a GET returns (e.g. a user-planted sticky marker to exercise the
# bot-identity filter in upsert_sticky_comment). Empty by default — most tests post fresh.
self.issue_comments: dict[tuple[str, int], list[dict]] = {}
@@ -138,6 +141,12 @@ class GitHubRecorder:
self.collaborator_permissions: dict[tuple[str, str], str] = {}
# (repo, number) -> raw reaction dicts for the in-flight reviewer-bot wait; default none.
self.pr_reactions: dict[tuple[str, int], list[dict]] = {}
+ # (repo, number) -> id of the reaction stamphog's own add_pr_reaction posted, so a repeat POST
+ # returns the same id (GitHub's real idempotency) and a DELETE has something to clear.
+ self._own_reactions: dict[tuple[str, int], int] = {}
+ # Test hook: force every reaction POST to return this response (e.g. a 500) to
+ # exercise the client's fail-open path without monkeypatching bound methods.
+ self.reaction_response_override: FakeResponse | None = None
self.teams_by_login: dict[str, list[str]] = {}
self.policy_files: dict[str, str] = {}
self.github_writes: list[dict[str, Any]] = []
@@ -175,6 +184,10 @@ class GitHubRecorder:
per_page = int(params.get("per_page", 30))
items = self.pr_reactions.get((m.group("repo"), int(m.group("number"))), [])
return FakeResponse(200, json_data=items[per_page * (page - 1) : per_page * page])
+ if method == "POST" and (m := _PR_REACTIONS_RE.match(path)):
+ return self._add_reaction(m.group("repo"), int(m.group("number")), json_body)
+ if method == "DELETE" and (m := _PR_REACTION_DELETE_RE.match(path)):
+ return self._remove_reaction(m.group("repo"), int(m.group("number")), int(m.group("rid")))
if method == "GET" and (m := _CONTENTS_RE.match(path)):
return self._get_contents(m.group("path"))
if method == "POST" and path == "/graphql":
@@ -230,16 +243,60 @@ class GitHubRecorder:
return FakeResponse(200, text=content, headers={"Content-Type": "text/plain; charset=utf-8"})
def _graphql(self, body: dict) -> FakeResponse:
- login = str(((body.get("variables") or {}).get("login")) or "")
+ query = str(body.get("query") or "")
+ variables = body.get("variables") or {}
+ # Two GraphQL callers share /graphql: get_pr_review_threads and get_user_team_slugs. Route by
+ # the query's shape (only the review-threads query mentions reviewThreads).
+ if "reviewThreads" in query:
+ repo = f"{variables.get('owner', '')}/{variables.get('name', '')}"
+ number = int(variables.get("pr") or 0)
+ nodes = self.review_threads.get((repo, number), [])
+ data = {
+ "data": {
+ "repository": {
+ "pullRequest": {
+ "reviewThreads": {"pageInfo": {"hasNextPage": False, "endCursor": None}, "nodes": nodes}
+ }
+ }
+ }
+ }
+ return FakeResponse(200, json_data=data)
+ login = str(variables.get("login") or "")
slugs = self.teams_by_login.get(login, [])
- data = {"data": {"organization": {"teams": {"nodes": [{"slug": s} for s in slugs]}}}}
- return FakeResponse(200, json_data=data)
+ teams_data = {"data": {"organization": {"teams": {"nodes": [{"slug": s} for s in slugs]}}}}
+ return FakeResponse(200, json_data=teams_data)
def _record_write(self, kind: str, repo: str, number: int, body: dict | None) -> FakeResponse:
new_id = self._alloc_id()
self.github_writes.append({"kind": kind, "repo": repo, "number": number, "body": body or {}, "id": new_id})
return FakeResponse(201 if kind != "issue_comment_edit" else 200, json_data={"id": new_id})
+ def _add_reaction(self, repo: str, number: int, body: dict | None) -> FakeResponse:
+ """Mirror GitHub's real idempotency: a repeat POST with the same identity returns 200 + the
+ existing id instead of stacking a second reaction; only the first POST is a 201 creation."""
+ if self.reaction_response_override is not None:
+ return self.reaction_response_override
+ content = (body or {}).get("content", "")
+ key = (repo, number)
+ existing_id = self._own_reactions.get(key)
+ if existing_id is not None:
+ return FakeResponse(200, json_data={"id": existing_id, "content": content})
+ new_id = self._alloc_id()
+ self._own_reactions[key] = new_id
+ self.github_writes.append(
+ {"kind": "add_reaction", "repo": repo, "number": number, "content": content, "id": new_id}
+ )
+ return FakeResponse(201, json_data={"id": new_id, "content": content})
+
+ def _remove_reaction(self, repo: str, number: int, reaction_id: int) -> FakeResponse:
+ key = (repo, number)
+ if self._own_reactions.get(key) == reaction_id:
+ del self._own_reactions[key]
+ self.github_writes.append(
+ {"kind": "remove_reaction", "repo": repo, "number": number, "reaction_id": reaction_id}
+ )
+ return FakeResponse(204)
+
def _remove_label(self, repo: str, number: int, label: str) -> FakeResponse:
self.github_writes.append({"kind": "remove_label", "repo": repo, "number": number, "label": label})
return FakeResponse(200, json_data=[])
@@ -248,6 +305,11 @@ class GitHubRecorder:
self.github_writes.append(
{"kind": "dismiss_review", "repo": repo, "number": number, "review_id": review_id, "body": body or {}}
)
+ # Reflect the dismissal in the reviews list like real GitHub does (state -> DISMISSED), so a
+ # subsequent get_pr_reviews / list_own_active_approvals no longer sees it as active.
+ for review in self.pr_reviews.get((repo, number), []):
+ if review.get("id") == review_id:
+ review["state"] = "DISMISSED"
return FakeResponse(200, json_data={})
@@ -258,6 +320,39 @@ def _extract(query: str, prefix: str) -> str:
return ""
+def review_thread_node(
+ *,
+ path: str,
+ comments: list[tuple[str, str]],
+ is_resolved: bool = False,
+ is_outdated: bool = False,
+ line: int | None = 1,
+ author_association: str = "MEMBER",
+ author_typename: str = "User",
+ comments_have_next_page: bool = False,
+ thread_id: str = "RT_1",
+) -> dict[str, Any]:
+ """Build one GraphQL reviewThreads node (what get_pr_review_threads parses), from (author, body) pairs."""
+ return {
+ "id": thread_id,
+ "isResolved": is_resolved,
+ "isOutdated": is_outdated,
+ "path": path,
+ "line": line,
+ "comments": {
+ "pageInfo": {"hasNextPage": comments_have_next_page, "endCursor": "cc"},
+ "nodes": [
+ {
+ "author": {"login": author, "__typename": author_typename},
+ "authorAssociation": author_association,
+ "body": body,
+ }
+ for author, body in comments
+ ],
+ },
+ }
+
+
def noop_remember_observed_core_limit(*args: Any, **kwargs: Any) -> None:
"""The limiter's response inspector — the fake response carries no rate headers."""
return None
diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.py
index 6c1444ec9ce3..c1dc39743ad9 100644
--- a/products/stamphog/backend/tests/test_api.py
+++ b/products/stamphog/backend/tests/test_api.py
@@ -286,6 +286,8 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
assert response.status_code == status.HTTP_200_OK, response.content
mock_exchange.assert_called_once_with("oauth-code")
mock_verify.assert_called_once_with("42", "user-token")
+ # The explicit-id path never discovers, so app_not_installed is always false there.
+ assert response.json()["app_not_installed"] is False
synced = sorted(row["repository"] for row in response.json()["synced"])
assert synced == ["PostHog/other", "PostHog/posthog"]
bound = StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id, installation_id="42")
@@ -404,6 +406,71 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
response = self.client.post(self.url, {"installation_id": "42", "state": self.state}, format="json")
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ @patch(f"{_VIEWS}.list_user_accessible_repositories", return_value=["PostHog/posthog"])
+ @patch(f"{_VIEWS}.list_user_installations", return_value=[{"id": "42", "account_login": "PostHog"}])
+ @patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")
+ def test_discovery_without_installation_id_syncs_discovered_installation(
+ self, mock_exchange, mock_discover, mock_list
+ ) -> None:
+ # Authorize-first: the callback carries no installation_id. The backend discovers the caller's
+ # installations from the OAuth code (GitHub returns only installations of this App the user can
+ # reach) and syncs them, so the client never has to supply a forgeable id.
+ response = self.client.post(self.url, {"code": "oauth-code", "state": self.state}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ mock_discover.assert_called_once_with("user-token")
+ body = response.json()
+ assert [row["repository"] for row in body["synced"]] == ["PostHog/posthog"]
+ assert body["app_not_installed"] is False
+ assert body["installations"] == []
+ bound = StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id, installation_id="42")
+ assert bound.count() == 1
+
+ @patch(f"{_VIEWS}.list_user_accessible_repositories")
+ @patch(
+ f"{_VIEWS}.list_user_installations",
+ return_value=[{"id": "100", "account_login": "AlphaOrg"}, {"id": "200", "account_login": "SharedOrg"}],
+ )
+ @patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")
+ def test_discovery_with_several_installations_binds_nothing_and_returns_choices(
+ self, mock_exchange, mock_discover, mock_list
+ ) -> None:
+ # Reachability is not intent: a user in several orgs that all carry the App must pick which
+ # installation this team binds. Binding them all would attach foreign orgs' repos here and, via
+ # the oldest-wins webhook resolution, could blackhole another team's future connect.
+ response = self.client.post(self.url, {"code": "oauth-code", "state": self.state}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert body["synced"] == []
+ assert body["skipped"] == []
+ assert body["app_not_installed"] is False
+ assert body["installations"] == [
+ {"id": "100", "account_login": "AlphaOrg"},
+ {"id": "200", "account_login": "SharedOrg"},
+ ]
+ mock_list.assert_not_called()
+ assert not StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id).exists()
+
+ @patch(f"{_VIEWS}.list_user_accessible_repositories")
+ @patch(f"{_VIEWS}.list_user_installations", return_value=[])
+ @patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")
+ def test_discovery_with_no_installations_reports_app_not_installed(
+ self, mock_exchange, mock_discover, mock_list
+ ) -> None:
+ # Discovery reached no installation the user can see: the App isn't installed anywhere for them.
+ # Not an error — return app_not_installed so the frontend routes them to the install page, binding
+ # nothing and never touching the repo-enumeration path.
+ response = self.client.post(self.url, {"code": "oauth-code", "state": self.state}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert body["app_not_installed"] is True
+ assert body["synced"] == []
+ assert body["skipped"] == []
+ mock_list.assert_not_called()
+ assert not StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id).exists()
+
class TestDigestChannelAPI(StamphogTeamScopedTestMixin, APIBaseTest):
databases = PRODUCT_DATABASES
@@ -425,6 +492,28 @@ class TestDigestChannelAPI(StamphogTeamScopedTestMixin, APIBaseTest):
assert channel.enabled is False
assert DigestChannel.objects.unscoped().filter(id=channel.id).exists()
+ def test_update_cannot_change_audience_key(self) -> None:
+ # audience_key anchors the digest bucket and its opt-out tombstone. A PATCH that re-pointed it
+ # would re-open an audience someone opted out of, so it's create-only — ignored on update while
+ # other fields (here slack_channel_name) still change.
+ integration = Integration.objects.create(
+ team_id=self.team.id, kind="slack", config={}, sensitive_config={"access_token": "x"}
+ )
+ created = self.client.post(
+ f"/api/projects/{self.team.id}/stamphog/digest_channels/",
+ {"audience_key": "team-x", "slack_integration_id": integration.id, "slack_channel_id": "C1"},
+ format="json",
+ ).json()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/stamphog/digest_channels/{created['id']}/",
+ {"audience_key": "team-evil", "slack_channel_name": "renamed"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert body["audience_key"] == "team-x"
+ assert body["slack_channel_name"] == "renamed"
+
def test_duplicate_audience_is_a_400_not_a_500(self) -> None:
# team_id is injected in perform_create, so DRF can't pre-validate the unique
# (team, audience_key) constraint — the IntegrityError must surface as a validation error.
diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.py
index 65a09c4ff480..31f5e223d844 100644
--- a/products/stamphog/backend/tests/test_digest.py
+++ b/products/stamphog/backend/tests/test_digest.py
@@ -5,9 +5,10 @@ from typing import Any
import pytest
from freezegun import freeze_time
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
-from django.db import transaction
+from django.db import OperationalError, transaction
+from django.db.models import QuerySet
from django.utils import timezone
from posthog.models.scoping import team_scope
@@ -125,6 +126,60 @@ def test_proof_of_post_persists_metadata_for_reclaim(team) -> None:
assert run.summary # the summary rode along with the proof-of-post, not just the message ts
+ "fail_times,expect_raise",
+ [(2, False), (3, True)],
+ ids=["retries_then_succeeds", "exhausts_and_propagates"],
+)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_proof_of_post_write_retries_transient_db_error(team, fail_times: int, expect_raise: bool) -> None:
+ # The proof-of-post write is the dedup proof: once Slack accepts, only slack_message_ts stops the
+ # reclaim sweeper from re-sending. A transient DB blip there must be retried (not taken at face
+ # value) or it converts into a duplicate Slack post. Slack is posted exactly once regardless; if the
+ # write never lands, the exception propagates with the PRs still linked to the PENDING run — the
+ # existing crash-window semantics the reclaim sweeper then handles.
+ channel_id = _seed_channel_and_prs(team.id, pr_count=2)
+ attempts = {"n": 0}
+ real_update = QuerySet.update
+
+ def flaky_update(self: Any, **kwargs: Any) -> int:
+ # Target only the proof-of-post write: it sets slack_message_ts but, unlike the completion
+ # write, carries no status/posted_at.
+ is_proof = "slack_message_ts" in kwargs and "status" not in kwargs and "posted_at" not in kwargs
+ if is_proof:
+ attempts["n"] += 1
+ if attempts["n"] <= fail_times:
+ raise OperationalError("transient db blip")
+ return real_update(self, **kwargs)
+
+ post = MagicMock(return_value="1234.5")
+ sleeps: list[float] = []
+ with (
+ patch("products.stamphog.backend.tasks.digest.post_digest", post),
+ patch("products.stamphog.backend.tasks.digest.summarize_merged_prs", side_effect=_summary),
+ patch("products.stamphog.backend.tasks.digest.time.sleep", side_effect=lambda s: sleeps.append(s)),
+ patch.object(QuerySet, "update", flaky_update),
+ ):
+ if expect_raise:
+ with pytest.raises(OperationalError):
+ send_digest_for_channel(digest_channel_id=channel_id, team_id=team.id)
+ else:
+ send_digest_for_channel(digest_channel_id=channel_id, team_id=team.id)
+
+ assert post.call_count == 1 # Slack posted exactly once either way
+ with team_scope(team.id):
+ run = DigestRun.objects.get()
+ linked = PullRequest.objects.filter(digest_run_id=run.id).count()
+ if expect_raise:
+ assert run.status == DigestRunStatus.PENDING # never finalized
+ assert linked == 2 # PRs stay linked to the PENDING run for the reclaim sweeper
+ assert len(sleeps) == fail_times - 1 # slept between the 3 attempts, not after the last
+ else:
+ assert run.status == DigestRunStatus.COMPLETED
+ assert run.pr_count == 2
+ assert len(sleeps) == fail_times
+
+
# ---- Finding 2: a channel's digest must never post to Slack twice ------------------------------
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index e75cf6092f81..02208c643589 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -6,6 +6,7 @@ from pathlib import Path
import pytest
from unittest.mock import MagicMock, patch
+from django.test import override_settings
from django.utils import timezone
from posthog.models import OAuthAccessToken, Team
@@ -27,6 +28,7 @@ from products.stamphog.backend.temporal.activities import (
MarkReviewFailedInput,
StamphogReviewInput,
dismiss_stale_approvals,
+ fetch_review_context,
list_in_flight_reviewer_bots,
mark_review_failed,
post_verdict,
@@ -172,6 +174,13 @@ def test_signed_webhook_drives_review_and_posts_approval(team, stamphog_chain: S
assert approvals[0]["body"]["event"] == "APPROVE"
assert approvals[0]["body"]["commit_id"] == head_sha
+ # signal_review_started posts a "review in flight" 👀 right after the stale-approval sweep, and
+ # post_verdict removes it once the verdict lands — the same reaction, added once and removed once.
+ additions = [w for w in recorder.github_writes if w["kind"] == "add_reaction"]
+ removals = [w for w in recorder.github_writes if w["kind"] == "remove_reaction"]
+ assert len(additions) == 1
+ assert [r["reaction_id"] for r in removals] == [additions[0]["id"]]
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_sandbox_destroy_failure_does_not_mask_a_completed_review(team, stamphog_chain: StamphogChain) -> None:
@@ -281,6 +290,53 @@ def test_failed_run_still_dismisses_the_stale_approval_first(team, stamphog_chai
assert [w["review_id"] for w in dismissals] == [777]
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_signal_review_started_posts_eyes_and_persists_reaction_id(team, stamphog_chain: StamphogChain) -> None:
+ # The moment a run commits to reviewing, it should show the same "review in flight" 👀 signal
+ # STAMPHOG_TRUSTED_REACTOR_BOTS reads off other reviewer bots — and the reaction id must be
+ # persisted so the terminal activities can find and remove it again.
+ repo_config = _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=141, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha="sha141a", status=ReviewRunStatus.QUEUED
+ )
+
+ _run_activity(activities.signal_review_started, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ additions = [w for w in recorder.github_writes if w["kind"] == "add_reaction"]
+ assert len(additions) == 1
+ assert additions[0]["content"] == "eyes"
+ run.refresh_from_db()
+ assert run.output["own_eyes_reaction_id"] == additions[0]["id"]
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_signal_review_started_reaction_failure_does_not_fail_the_activity(team, stamphog_chain: StamphogChain) -> None:
+ # add_pr_reaction is deliberately the one fail-open call on this client (see its docstring): a
+ # GitHub hiccup posting the cosmetic 👀 must never fail or retry the review run itself.
+ repo_config = _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ recorder.reaction_response_override = fakes.FakeResponse(500, text="rate limited")
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=142, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha="sha142a", status=ReviewRunStatus.QUEUED
+ )
+
+ result = _run_activity(
+ activities.signal_review_started, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id)
+ )
+
+ assert result == {"reaction_id": None}
+ run.refresh_from_db()
+ assert run.output["own_eyes_reaction_id"] is None
+ assert run.status == ReviewRunStatus.QUEUED # the activity neither raised nor marked the run failed
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_hosted_review_fails_closed_without_gateway_instead_of_anthropic_fallback(
team, stamphog_chain: StamphogChain
@@ -417,6 +473,266 @@ def test_dismiss_stale_approvals(
assert prior.approval_dismissed_at is None
+ "slug,review_login,review_type,review_state,expect_github_dismissed",
+ [
+ ("stamphog", "stamphog[bot]", "Bot", "APPROVED", True),
+ # Slug unset: write-adjacent decisions must not act on a fuzzy "any Bot" match, so nothing.
+ ("", "stamphog[bot]", "Bot", "APPROVED", False),
+ # A foreign bot's approval is not ours to dismiss.
+ ("stamphog", "other-app[bot]", "Bot", "APPROVED", False),
+ # An already-inactive (dismissed) review is not active, so nothing to do.
+ ("stamphog", "stamphog[bot]", "Bot", "DISMISSED", False),
+ ],
+ ids=["orphan_swept", "slug_unset_no_op", "foreign_bot_untouched", "already_dismissed_untouched"],
+)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_dismiss_stale_approvals_github_side_sweep(
+ team,
+ stamphog_chain: StamphogChain,
+ slug: str,
+ review_login: str,
+ review_type: str,
+ review_state: str,
+ expect_github_dismissed: bool,
+) -> None:
+ # The DB sweep keys off posted_review_id, so an approval this App left on GitHub with NO ReviewRun
+ # row carrying its id is an invisible orphan that stands forever. The GitHub-side belt-and-braces
+ # sweep must dismiss our own still-active approval — and only ours, and only with a configured slug.
+ repo_config = _repo_config(team.id)
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=130, author_login="devex-dev"
+ )
+ current = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha="sha-new", status=ReviewRunStatus.QUEUED
+ )
+ # An active approval on GitHub with no ReviewRun.posted_review_id pointing at it — the orphan.
+ stamphog_chain.recorder.pr_reviews[(REPO, 130)] = [
+ {
+ "id": 6161,
+ "state": review_state,
+ "commit_id": "sha-old",
+ "user": {"login": review_login, "type": review_type},
+ }
+ ]
+
+ with override_settings(STAMPHOG_GITHUB_APP_SLUG=slug):
+ result = _run_activity(
+ dismiss_stale_approvals, StamphogReviewInput(review_run_id=str(current.id), team_id=team.id)
+ )
+
+ dismissals = [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "dismiss_review"]
+ if expect_github_dismissed:
+ assert [d["review_id"] for d in dismissals] == [6161]
+ assert result["github_dismissed"] == 1
+ else:
+ assert dismissals == []
+ assert result["github_dismissed"] == 0
+
+
+ "slug,review_state,review_commit_matches,review_login,review_type,expect_adopt",
+ [
+ ("stamphog", "APPROVED", True, "stamphog[bot]", "Bot", True),
+ # Approval at a different commit doesn't cover this head — post fresh.
+ ("stamphog", "APPROVED", False, "stamphog[bot]", "Bot", False),
+ # A non-bot or wrong-login author isn't ours — post fresh.
+ ("stamphog", "APPROVED", True, "someone", "User", False),
+ ("stamphog", "APPROVED", True, "other-app[bot]", "Bot", False),
+ # A dismissed review is not active — post fresh.
+ ("stamphog", "DISMISSED", True, "stamphog[bot]", "Bot", False),
+ # Slug unset: never adopt off a fuzzy match — post fresh.
+ ("", "APPROVED", True, "stamphog[bot]", "Bot", False),
+ ],
+ ids=[
+ "adopt_own_active_approval_at_head",
+ "different_commit_posts_fresh",
+ "non_bot_posts_fresh",
+ "wrong_login_bot_posts_fresh",
+ "dismissed_posts_fresh",
+ "slug_unset_posts_fresh",
+ ],
+)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_post_verdict_adopts_own_orphan_approval_instead_of_reposting(
+ team,
+ stamphog_chain: StamphogChain,
+ slug: str,
+ review_state: str,
+ review_commit_matches: bool,
+ review_login: str,
+ review_type: str,
+ expect_adopt: bool,
+) -> None:
+ # A prior post_verdict attempt could have posted the approval to GitHub, then crashed before
+ # persisting posted_review_id. On retry, re-posting would stack a SECOND standing approval the
+ # DB-keyed sweep can never see. So post_verdict must adopt an existing active APPROVE pinned to
+ # exactly this head instead of posting again — but only when it's provably ours (exact bot login,
+ # active state, matching commit), else it posts fresh.
+ repo_config = _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ head_sha = "sha131a"
+ recorder.register_pr(REPO, 131, _pr_object(131, "devex-dev", head_sha), _pr_files())
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=131, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id,
+ pull_request=pull_request,
+ head_sha=head_sha,
+ status=ReviewRunStatus.REVIEWING,
+ output={"reviewer_raw": fakes.approved_engine_output().splitlines()[-1]},
+ )
+ recorder.pr_reviews[(REPO, 131)] = [
+ {
+ "id": 4242,
+ "state": review_state,
+ "commit_id": head_sha if review_commit_matches else "some-other-sha",
+ "user": {"login": review_login, "type": review_type},
+ }
+ ]
+
+ with override_settings(STAMPHOG_GITHUB_APP_SLUG=slug):
+ result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ assert result == {"verdict": str(ReviewVerdict.APPROVED)}
+ approvals = [w for w in recorder.github_writes if w["kind"] == "approve_review"]
+ run.refresh_from_db()
+ assert run.status == ReviewRunStatus.COMPLETED
+ assert run.verdict == ReviewVerdict.APPROVED
+ if expect_adopt:
+ assert approvals == [] # adopted the existing approval, never posted a second
+ assert run.posted_review_id == 4242
+ else:
+ assert len(approvals) == 1
+ assert run.posted_review_id == approvals[0]["id"]
+
+
+ "include_peer_live_approval",
+ [False, True],
+ ids=["orphan_only_swept", "peer_live_approval_kept"],
+)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_non_approve_terminal_sweeps_supersession_orphan(
+ team, stamphog_chain: StamphogChain, include_peer_live_approval: bool
+) -> None:
+ # Supersession orphan race: an older run cleared post_verdict's guards, got superseded, then landed its
+ # GitHub approval AFTER this newer run's startup sweep already ran. This newer run refuses, so nothing
+ # would list our approvals again — the terminal sweep on the refusing run must retract the orphan, or it
+ # keeps satisfying branch protection over a refusing verdict. The keep-set case seeds a NEWER run's
+ # legitimately-persisted approval too: that one must survive the sweep.
+ repo_config = _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ head_sha = "sha-refused"
+ recorder.register_pr(REPO, 150, _pr_object(150, "devex-dev", head_sha))
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=150, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id,
+ pull_request=pull_request,
+ head_sha=head_sha,
+ status=ReviewRunStatus.REVIEWING,
+ output={"reviewer_raw": _refused_engine_output()},
+ )
+ # The orphan: an active APPROVE by our bot at an older head, with no live ReviewRun pointing at it.
+ github_reviews = [
+ {"id": 8181, "state": "APPROVED", "commit_id": "sha-old", "user": {"login": "stamphog[bot]", "type": "Bot"}}
+ ]
+ if include_peer_live_approval:
+ ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id,
+ pull_request=pull_request,
+ head_sha="sha-newer",
+ status=ReviewRunStatus.COMPLETED,
+ verdict=ReviewVerdict.APPROVED,
+ posted_review_id=9191,
+ )
+ github_reviews.append(
+ {
+ "id": 9191,
+ "state": "APPROVED",
+ "commit_id": "sha-newer",
+ "user": {"login": "stamphog[bot]", "type": "Bot"},
+ }
+ )
+ recorder.pr_reviews[(REPO, 150)] = github_reviews
+
+ with override_settings(STAMPHOG_GITHUB_APP_SLUG="stamphog"):
+ result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ assert result == {"verdict": str(ReviewVerdict.REFUSED)}
+ run.refresh_from_db()
+ assert run.verdict == ReviewVerdict.REFUSED
+ # The orphan is always swept; a peer run's live persisted approval (9191) is never touched.
+ dismissals = [w for w in recorder.github_writes if w["kind"] == "dismiss_review"]
+ assert [d["review_id"] for d in dismissals] == [8181]
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_failed_run_terminal_sweeps_supersession_orphan(team, stamphog_chain: StamphogChain) -> None:
+ # A newer run that FAILS leaves the same exposure a refusing one does: an older superseded run's
+ # approval can land on GitHub after this run's startup sweep, and a FAILED run never lists approvals
+ # again. mark_review_failed must run the GitHub-side sweep at its terminal to retract that orphan.
+ repo_config = _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=151, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha="sha151a", status=ReviewRunStatus.REVIEWING
+ )
+ recorder.pr_reviews[(REPO, 151)] = [
+ {"id": 8282, "state": "APPROVED", "commit_id": "sha-old", "user": {"login": "stamphog[bot]", "type": "Bot"}}
+ ]
+
+ with override_settings(STAMPHOG_GITHUB_APP_SLUG="stamphog"):
+ _run_activity(
+ mark_review_failed,
+ MarkReviewFailedInput(review_run_id=str(run.id), team_id=team.id, error="worker lost"),
+ )
+
+ run.refresh_from_db()
+ assert run.status == ReviewRunStatus.FAILED
+ dismissals = [w for w in recorder.github_writes if w["kind"] == "dismiss_review"]
+ assert [d["review_id"] for d in dismissals] == [8282]
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_fetch_review_context_carries_inline_review_threads(team, stamphog_chain: StamphogChain) -> None:
+ # A maintainer's unresolved inline "do not merge" lives only on the GraphQL review-threads surface;
+ # fetch_review_context must carry it onto run.output so the sandbox reviewer sees the blocker.
+ repo_config = _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ head_sha = "sha132a"
+ recorder.register_pr(REPO, 132, _pr_object(132, "devex-dev", head_sha), _pr_files())
+ recorder.review_threads[(REPO, 132)] = [
+ fakes.review_thread_node(path="src/util.py", comments=[("maintainer", "do not merge")], is_resolved=False)
+ ]
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=132, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha=head_sha, status=ReviewRunStatus.QUEUED
+ )
+
+ _run_activity(fetch_review_context, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ run.refresh_from_db()
+ assert run.output["review_threads"] == [
+ {
+ "is_resolved": False,
+ "is_outdated": False,
+ "path": "src/util.py",
+ "line": 1,
+ "comments": [
+ {"author": "maintainer", "author_association": "MEMBER", "author_is_bot": False, "body": "do not merge"}
+ ],
+ }
+ ]
+
+
@pytest.mark.parametrize(
"raw_error,expected_stored",
[
@@ -641,7 +957,8 @@ def test_bot_eyes_on_a_later_reactions_page_still_counts_as_in_flight(team, stam
def test_mark_review_failed_dismisses_an_orphaned_approval(team, stamphog_chain: StamphogChain) -> None:
# post_verdict can approve on GitHub, persist the id, and then exhaust retries before the
# terminal save — the workflow's failure path is the last chance to retract that approval:
- # without a future delivery, nothing else ever sweeps a FAILED run's orphan.
+ # without a future delivery, nothing else ever sweeps a FAILED run's orphan. It's also the last
+ # chance to remove the "review in flight" 👀 signal_review_started posted for this same run.
repo_config = _repo_config(team.id)
pull_request = PullRequest.objects.for_team(team.id).create(
team_id=team.id, repo_config=repo_config, pr_number=119, author_login="devex-dev"
@@ -652,6 +969,7 @@ def test_mark_review_failed_dismisses_an_orphaned_approval(team, stamphog_chain:
head_sha="sha119a",
status=ReviewRunStatus.REVIEWING,
posted_review_id=888,
+ output={"own_eyes_reaction_id": 777},
)
with patch("products.stamphog.backend.temporal.activities.ph_scoped_capture") as mock_capture_cm:
@@ -661,6 +979,8 @@ def test_mark_review_failed_dismisses_an_orphaned_approval(team, stamphog_chain:
dismissals = [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "dismiss_review"]
assert [d["review_id"] for d in dismissals] == [888]
+ removals = [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "remove_reaction"]
+ assert [r["reaction_id"] for r in removals] == [777]
run.refresh_from_db()
assert run.status == ReviewRunStatus.FAILED
assert run.approval_dismissed_at is not None
diff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.py
index f18412a2874f..5f0198c7190f 100644
--- a/products/stamphog/backend/tests/test_logic.py
+++ b/products/stamphog/backend/tests/test_logic.py
@@ -1,18 +1,24 @@
import json
+from collections.abc import Callable
import pytest
from unittest.mock import patch
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
+
+import jwt
+from parameterized import parameterized
from products.stamphog.backend.logic.digest import DigestPRSummary, DigestSummary
from products.stamphog.backend.logic.digest_config import load_repo_digest_config
-from products.stamphog.backend.logic.github_client import StamphogGitHubError
+from products.stamphog.backend.logic.github_client import StamphogGitHubClient, StamphogGitHubError, _build_app_jwt
from products.stamphog.backend.logic.reviewer import build_reviewer_invocation, parse_reviewer_output
from products.stamphog.backend.logic.slack_digest import _build_blocks, _build_fallback_text
from products.stamphog.backend.models import StamphogRepoConfig
from products.stamphog.backend.temporal import activities as activities_module
from products.stamphog.backend.temporal.registry import ACTIVITIES
+from products.stamphog.backend.tests import fakes
+from products.stamphog.backend.tests.conftest import _generate_app_private_key
# The gate/policy engine now lives in tools/pr-approval-agent and is covered by its
# own suite (test_gates.py, test_policy.py); it runs inside the sandbox rather than
@@ -88,16 +94,21 @@ class ParseReviewerOutputTests(SimpleTestCase):
class BuildReviewerInvocationTests(SimpleTestCase):
- def test_reviews_are_threaded_into_the_context(self) -> None:
+ def test_reviews_and_review_threads_are_threaded_into_the_context(self) -> None:
# The hosted reviewer must receive prior PR reviews so the engine's prerequisite gate can block
- # on an active CHANGES_REQUESTED. If reviews were dropped from the context the reviewer would run
- # review-blind and could approve over a maintainer's block.
+ # on an active CHANGES_REQUESTED, and inline review threads so a maintainer's unresolved "do not
+ # merge" reaches the prompt. If either were dropped from the context the reviewer would run
+ # partly blind and could approve over a block it never saw.
reviews = [{"user": {"login": "maintainer"}, "state": "CHANGES_REQUESTED"}]
+ review_threads = [
+ {"is_resolved": False, "is_outdated": False, "path": "a.py", "comments": [{"author": "m", "body": "hold"}]}
+ ]
invocation = build_reviewer_invocation(
pr={"number": 1},
files=[],
reviews=reviews,
discussion=[],
+ review_threads=review_threads,
check_runs=[],
pr_reactions=[],
author_pr_numbers=[],
@@ -109,6 +120,7 @@ class BuildReviewerInvocationTests(SimpleTestCase):
)
context = json.loads(invocation.context_json)
assert context["reviews"] == reviews
+ assert context["review_threads"] == review_threads
class SlackDigestEscapingTests(SimpleTestCase):
@@ -158,6 +170,219 @@ class DigestConfigFetchTests(SimpleTestCase):
load_repo_digest_config(config)
+_GH = "products.stamphog.backend.logic.github_client"
+
+
+class GetPrReviewThreadsTests(SimpleTestCase):
+ def _fetch(self, *graphql_responses: fakes.FakeResponse) -> list[dict]:
+ # Stub the network boundary (github_request): the access-token mint is answered so the client's
+ # _request machinery runs for real, and /graphql calls consume the scripted responses in order
+ # (the last one repeats, so single-response tests behave as before).
+ remaining = list(graphql_responses)
+
+ def fake_request(method: str, url: str, **kwargs: object) -> fakes.FakeResponse:
+ if url.endswith("/access_tokens"):
+ return fakes.FakeResponse(201, json_data={"token": "t", "expires_at": "2999-01-01T00:00:00Z"})
+ return remaining.pop(0) if len(remaining) > 1 else remaining[0]
+
+ with (
+ override_settings(STAMPHOG_GITHUB_APP_ID="1", STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key()),
+ patch(f"{_GH}.github_request", fake_request),
+ patch(f"{_GH}.remember_observed_core_limit", lambda *a, **k: None),
+ patch(f"{_GH}.raise_if_github_rate_limited", lambda *a, **k: None),
+ ):
+ return StamphogGitHubClient("123").get_pr_review_threads("acme/widgets", 5)
+
+ def _threads_page(self, nodes: list[dict], *, has_next: bool) -> fakes.FakeResponse:
+ payload = {
+ "data": {
+ "repository": {
+ "pullRequest": {
+ "reviewThreads": {"pageInfo": {"hasNextPage": has_next, "endCursor": "c"}, "nodes": nodes}
+ }
+ }
+ }
+ }
+ return fakes.FakeResponse(200, json_data=payload)
+
+ def test_parses_lean_shape_and_trims_body(self) -> None:
+ # The lean shape must carry the author identity triple — the engine's author-trust gate needs
+ # it, or an untrusted external commenter could plant a fake maintainer hold in the prompt.
+ node = fakes.review_thread_node(
+ path="src/util.py",
+ comments=[("maintainer", "x" * 5000)],
+ is_resolved=True,
+ is_outdated=False,
+ line=42,
+ author_association="MEMBER",
+ author_typename="User",
+ )
+ threads = self._fetch(self._threads_page([node], has_next=False))
+ assert threads == [
+ {
+ "is_resolved": True,
+ "is_outdated": False,
+ "path": "src/util.py",
+ "line": 42,
+ "comments": [
+ {
+ "author": "maintainer",
+ "author_association": "MEMBER",
+ "author_is_bot": False,
+ "body": "x" * 4000,
+ }
+ ],
+ }
+ ]
+
+ @parameterized.expand(
+ [
+ ("graphql_errors", fakes.FakeResponse(200, json_data={"errors": [{"message": "no access"}]})),
+ ("http_failure", fakes.FakeResponse(500, text="boom")),
+ ]
+ )
+ def test_fails_closed(self, _name: str, response: fakes.FakeResponse) -> None:
+ # A silently truncated or errored thread list reads as "no blockers" to the reviewer, the one
+ # wrong answer here — every failure mode must raise, exactly like get_pr_discussion.
+ with pytest.raises(StamphogGitHubError):
+ self._fetch(response)
+
+ def _thread_comments_page(self, comments: list[tuple[str, str]], *, has_next: bool) -> fakes.FakeResponse:
+ payload = {
+ "data": {
+ "node": {
+ "comments": {
+ "pageInfo": {"hasNextPage": has_next, "endCursor": "cc2"},
+ "nodes": [
+ {
+ "author": {"login": author, "__typename": "User"},
+ "authorAssociation": "MEMBER",
+ "body": body,
+ }
+ for author, body in comments
+ ],
+ }
+ }
+ }
+ }
+ return fakes.FakeResponse(200, json_data=payload)
+
+ def test_comment_page_overflow_pages_the_tail(self) -> None:
+ # A >window thread must not fail the review (one chatty thread would make the PR permanently
+ # unreviewable) NOR silently drop its tail (comment 51 could be a maintainer's hold): the tail
+ # pages via the per-thread query and lands appended, in order.
+ node = fakes.review_thread_node(
+ path="src/util.py", comments=[("maintainer", "hold")], comments_have_next_page=True
+ )
+ threads = self._fetch(
+ self._threads_page([node], has_next=False),
+ self._thread_comments_page([("maintainer", "still holding")], has_next=False),
+ )
+ assert [c["body"] for c in threads[0]["comments"]] == ["hold", "still holding"]
+
+ def test_comment_tail_page_cap_fails_closed(self) -> None:
+ # A thread whose comment tail never stops paginating (pathological) must raise rather than
+ # return a thread the reviewer would read as complete.
+ node = fakes.review_thread_node(
+ path="src/util.py", comments=[("maintainer", "hold")], comments_have_next_page=True
+ )
+ with pytest.raises(StamphogGitHubError):
+ self._fetch(
+ self._threads_page([node], has_next=False),
+ self._thread_comments_page([("maintainer", "more")], has_next=True),
+ )
+
+ def test_page_cap_fails_closed(self) -> None:
+ # A PR whose threads never stop paginating must raise rather than review a truncated list.
+ with pytest.raises(StamphogGitHubError):
+ self._fetch(self._threads_page([], has_next=True))
+
+
+# add_pr_reaction / remove_pr_reaction are deliberately the one fail-open pair on the client
+# (see their docstrings): a cosmetic "review in flight" 👀 must never fail or retry the calling
+# review activity, unlike every other read/write on StamphogGitHubClient.
+class PrReactionFailOpenTests(SimpleTestCase):
+ def _call(
+ self,
+ transport_response_or_error: fakes.FakeResponse | Exception,
+ call: Callable[[StamphogGitHubClient], object],
+ ) -> object:
+ def fake_request(method: str, url: str, **kwargs: object) -> fakes.FakeResponse:
+ if url.endswith("/access_tokens"):
+ return fakes.FakeResponse(201, json_data={"token": "t", "expires_at": "2999-01-01T00:00:00Z"})
+ if isinstance(transport_response_or_error, Exception):
+ raise transport_response_or_error
+ return transport_response_or_error
+
+ with (
+ override_settings(STAMPHOG_GITHUB_APP_ID="1", STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key()),
+ patch(f"{_GH}.github_request", fake_request),
+ patch(f"{_GH}.remember_observed_core_limit", lambda *a, **k: None),
+ patch(f"{_GH}.raise_if_github_rate_limited", lambda *a, **k: None),
+ ):
+ return call(StamphogGitHubClient("123"))
+
+ @parameterized.expand(
+ [
+ ("http_error", fakes.FakeResponse(500, text="boom")),
+ ("non_json_body", fakes.FakeResponse(201, text="not json")),
+ ("transport_exception", RuntimeError("network blew up")),
+ ]
+ )
+ def test_add_pr_reaction_fails_open(self, _name: str, failure: fakes.FakeResponse | Exception) -> None:
+ result = self._call(failure, lambda c: c.add_pr_reaction("acme/widgets", 5))
+ assert result is None
+
+ @parameterized.expand(
+ [
+ ("http_error", fakes.FakeResponse(500, text="boom")),
+ ("transport_exception", RuntimeError("network blew up")),
+ ]
+ )
+ def test_remove_pr_reaction_fails_open(self, _name: str, failure: fakes.FakeResponse | Exception) -> None:
+ # Must not raise — a failed removal is cosmetic cleanup, never worth retrying the activity.
+ self._call(failure, lambda c: c.remove_pr_reaction("acme/widgets", 5, 999))
+
+ def test_remove_pr_reaction_404_is_a_benign_noop(self) -> None:
+ self._call(fakes.FakeResponse(404, text="not found"), lambda c: c.remove_pr_reaction("acme/widgets", 5, 999))
+
+ def test_add_pr_reaction_200_returns_the_existing_id_not_a_new_one(self) -> None:
+ # GitHub's own idempotency: reacting again with the same identity+content returns 200 with the
+ # EXISTING reaction rather than 201 with a new one — the client must surface that id either way.
+ response = fakes.FakeResponse(200, json_data={"id": 555, "content": "eyes"})
+ result = self._call(response, lambda c: c.add_pr_reaction("acme/widgets", 5))
+ assert result == 555
+
+
+class BuildAppJwtIssuerTests(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("client_id_preferred_over_app_id", "acme-client", "999", "acme-client"),
+ ("app_id_fallback_when_client_id_unset", "", "999", "999"),
+ ]
+ )
+ def test_issuer_prefers_client_id_falling_back_to_app_id(
+ self, _name: str, client_id: str, app_id: str, expected_issuer: str
+ ) -> None:
+ with override_settings(
+ STAMPHOG_GITHUB_APP_CLIENT_ID=client_id,
+ STAMPHOG_GITHUB_APP_ID=app_id,
+ STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key(),
+ ):
+ token = _build_app_jwt()
+ claims = jwt.decode(token, options={"verify_signature": False})
+ assert claims["iss"] == expected_issuer
+
+ def test_raises_when_neither_client_id_nor_app_id_is_configured(self) -> None:
+ with override_settings(
+ STAMPHOG_GITHUB_APP_CLIENT_ID="",
+ STAMPHOG_GITHUB_APP_ID="",
+ STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key(),
+ ):
+ with pytest.raises(StamphogGitHubError):
+ _build_app_jwt()
+
+
class TemporalRegistryTests(SimpleTestCase):
def test_every_defined_activity_is_registered_with_the_worker(self) -> None:
# A new @activity.defn that isn't added to ACTIVITIES fails only at runtime, when the worker
diff --git a/products/stamphog/backend/tests/test_presentation.py b/products/stamphog/backend/tests/test_presentation.py
index 1e599a4655cb..467da3500e40 100644
--- a/products/stamphog/backend/tests/test_presentation.py
+++ b/products/stamphog/backend/tests/test_presentation.py
@@ -25,7 +25,7 @@ def _request(body: bytes, *, event: str = "pull_request", delivery_id: str = "de
return factory.post("/stamphog/webhook/", data=body, content_type="application/json", **headers)
-@override_settings(STAMPHOG_GITHUB_WEBHOOK_SECRET=WEBHOOK_SECRET)
+@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET)
@patch("products.stamphog.backend.presentation.webhooks.process_pull_request_event.delay")
def test_valid_pull_request_event_enqueues_and_returns_202(mock_delay):
body = json.dumps({"action": "opened"}).encode("utf-8")
@@ -37,7 +37,7 @@ def test_valid_pull_request_event_enqueues_and_returns_202(mock_delay):
mock_delay.assert_called_once_with(payload={"action": "opened"}, delivery_id="delivery-1")
-@override_settings(STAMPHOG_GITHUB_WEBHOOK_SECRET=WEBHOOK_SECRET)
+@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET)
@patch("products.stamphog.backend.presentation.webhooks.process_pull_request_event.delay")
def test_non_pull_request_event_is_acked_without_enqueueing(mock_delay):
body = json.dumps({"action": "created"}).encode("utf-8")
@@ -54,7 +54,7 @@ def test_non_pull_request_event_is_acked_without_enqueueing(mock_delay):
[None, "sha256=" + "0" * 64],
ids=["missing_signature", "wrong_signature"],
)
-@override_settings(STAMPHOG_GITHUB_WEBHOOK_SECRET=WEBHOOK_SECRET)
+@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET)
@patch("products.stamphog.backend.presentation.webhooks.process_pull_request_event.delay")
def test_invalid_signature_is_rejected(mock_delay, signature):
body = json.dumps({"action": "opened"}).encode("utf-8")
@@ -66,7 +66,7 @@ def test_invalid_signature_is_rejected(mock_delay, signature):
mock_delay.assert_not_called()
-@override_settings(STAMPHOG_GITHUB_WEBHOOK_SECRET="")
+@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET="")
def test_missing_secret_configuration_returns_500():
body = json.dumps({"action": "opened"}).encode("utf-8")
request = _request(body, signature=_signature(body, "irrelevant"))
diff --git a/products/stamphog/frontend/generated/api.schemas.ts b/products/stamphog/frontend/generated/api.schemas.ts
index d45d93383185..60056a7820ff 100644
--- a/products/stamphog/frontend/generated/api.schemas.ts
+++ b/products/stamphog/frontend/generated/api.schemas.ts
@@ -25,7 +25,7 @@ export const ResolutionSourceEnumApi = {
export interface DigestChannelApi {
readonly id: string
/**
- * Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'.
+ * Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'. Immutable after creation — it anchors the audience and its opt-out tombstone.
* @maxLength 255
*/
audience_key: string
@@ -72,7 +72,7 @@ export interface PaginatedDigestChannelListApi {
export interface PatchedDigestChannelApi {
readonly id?: string
/**
- * Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'.
+ * Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'. Immutable after creation — it anchors the audience and its opt-out tombstone.
* @maxLength 255
*/
audience_key?: string
@@ -295,26 +295,40 @@ export interface PatchedStamphogRepoConfigApi {
export interface StamphogInstallInfoApi {
/** URL-friendly slug of the dedicated Stamphog GitHub App, or blank if unconfigured. */
readonly app_slug: string
- /** GitHub install URL (github.com/apps/<slug>/installations/new) the user opens to install the App, or blank if the App slug is unconfigured. */
+ /** GitHub install URL (github.com/apps/<slug>/installations/new) the user opens to install the App, or blank if the App slug is unconfigured. Used for the genuinely-not-installed case; the primary 'Connect' button uses authorize_url instead. */
readonly install_url: string
+ /** GitHub authorize URL (github.com/login/oauth/authorize) the 'Connect' button opens. Authorize-first: an already-installed user is redirected straight back with an OAuth code (no installation_id), and sync_installation then discovers their installations server-side. Blank if the App client id is unconfigured. */
+ readonly authorize_url: string
}
/**
- * Request body for binding a completed GitHub App installation to the current team.
+ * Request body for binding a GitHub App installation to the current team.
*
- * Requires both the ``installation_id`` and the user-to-server OAuth ``code`` from the post-install
- * redirect: the code proves the caller actually owns the installation, without which any caller could
- * bind another org's installation to their own team.
+ * Always requires the user-to-server OAuth ``code`` (the ownership proof) and the ``state`` token.
+ * ``installation_id`` is optional: when present (the fresh-install redirect) exactly that installation
+ * is verified and synced; when absent or blank (the authorize-first redirect) the caller's accessible
+ * installations are discovered server-side from the code, so the client never has to supply a
+ * forgeable id.
*/
export interface StamphogSyncInstallationRequestApi {
- /** GitHub App installation ID returned on the post-install Setup URL redirect. */
- installation_id: string
+ /** GitHub App installation ID from the fresh-install Setup URL redirect. Optional: absent or blank means discover the caller's installations from the OAuth code instead (authorize-first flow). The id is not trusted on its own — ownership is always proven via the code. */
+ installation_id?: string
/** GitHub user-to-server OAuth code from the post-install redirect (present when the App has 'Request user authorization during installation' enabled). Exchanged server-side to prove the caller owns the installation before its repos are bound. */
code: string
/** Signed state token minted by install_info and round-tripped through GitHub's install redirect. Binds the callback to the team and user that started the flow, so a stolen installation_id + code can't be replayed against another team's session. */
state: string
}
+/**
+ * One installation of the App the authorizing user can reach, offered for an explicit pick.
+ */
+export interface StamphogDiscoveredInstallationApi {
+ /** GitHub installation id, as a string. */
+ readonly id: string
+ /** Login of the org or user account the installation lives on. */
+ readonly account_login: string
+}
+
/**
* Result of syncing an installation: rows created/kept for this team, plus conflicting repos skipped.
*/
@@ -323,6 +337,10 @@ export interface StamphogSyncInstallationResponseApi {
readonly synced: readonly StamphogRepoConfigApi[]
/** Repository full names skipped because another team already owns them under this installation. */
readonly skipped: readonly string[]
+ /** True only on the discovery path (no installation_id) when the caller can reach no installation of this App — it isn't installed anywhere they can see. The frontend should route the user to the GitHub install page (install_url). Always false on the explicit installation_id path. */
+ readonly app_not_installed: boolean
+ /** Populated only on the discovery path when the caller can reach MORE than one installation of this App: nothing was bound, and the user must pick which installation to connect. The frontend re-runs the authorize flow and calls back with the chosen installation_id, which the explicit path verifies. Empty whenever a bind happened (or nothing was found). */
+ readonly installations: readonly StamphogDiscoveredInstallationApi[]
}
/**
diff --git a/products/stamphog/frontend/generated/api.zod.ts b/products/stamphog/frontend/generated/api.zod.ts
index fff00c24b7c4..020e51134514 100644
--- a/products/stamphog/frontend/generated/api.zod.ts
+++ b/products/stamphog/frontend/generated/api.zod.ts
@@ -25,7 +25,9 @@ export const StamphogDigestChannelsCreateBody = /* @__PURE__ */ zod.object({
audience_key: zod
.string()
.max(stamphogDigestChannelsCreateBodyAudienceKeyMax)
- .describe("Opaque digest bucket this channel receives, e.g. 'repo:PostHog\/posthog'."),
+ .describe(
+ "Opaque digest bucket this channel receives, e.g. 'repo:PostHog\/posthog'. Immutable after creation — it anchors the audience and its opt-out tombstone."
+ ),
slack_integration_id: zod
.number()
.min(stamphogDigestChannelsCreateBodySlackIntegrationIdMin)
@@ -59,7 +61,9 @@ export const StamphogDigestChannelsUpdateBody = /* @__PURE__ */ zod.object({
audience_key: zod
.string()
.max(stamphogDigestChannelsUpdateBodyAudienceKeyMax)
- .describe("Opaque digest bucket this channel receives, e.g. 'repo:PostHog\/posthog'."),
+ .describe(
+ "Opaque digest bucket this channel receives, e.g. 'repo:PostHog\/posthog'. Immutable after creation — it anchors the audience and its opt-out tombstone."
+ ),
slack_integration_id: zod
.number()
.min(stamphogDigestChannelsUpdateBodySlackIntegrationIdMin)
@@ -94,7 +98,9 @@ export const StamphogDigestChannelsPartialUpdateBody = /* @__PURE__ */ zod.objec
.string()
.max(stamphogDigestChannelsPartialUpdateBodyAudienceKeyMax)
.optional()
- .describe("Opaque digest bucket this channel receives, e.g. 'repo:PostHog\/posthog'."),
+ .describe(
+ "Opaque digest bucket this channel receives, e.g. 'repo:PostHog\/posthog'. Immutable after creation — it anchors the audience and its opt-out tombstone."
+ ),
slack_integration_id: zod
.number()
.min(stamphogDigestChannelsPartialUpdateBodySlackIntegrationIdMin)
@@ -235,11 +241,16 @@ export const StamphogRepoConfigsPartialUpdateBody = /* @__PURE__ */ zod.object({
/**
* Per-repo stamphog settings — enable/disable review, GitHub App installation, policy overrides.
*/
+export const stamphogRepoConfigsSyncInstallationCreateBodyInstallationIdDefault = ``
+
export const StamphogRepoConfigsSyncInstallationCreateBody = /* @__PURE__ */ zod
.object({
installation_id: zod
.string()
- .describe('GitHub App installation ID returned on the post-install Setup URL redirect.'),
+ .default(stamphogRepoConfigsSyncInstallationCreateBodyInstallationIdDefault)
+ .describe(
+ "GitHub App installation ID from the fresh-install Setup URL redirect. Optional: absent or blank means discover the caller's installations from the OAuth code instead (authorize-first flow). The id is not trusted on its own — ownership is always proven via the code."
+ ),
code: zod
.string()
.describe(
@@ -252,5 +263,5 @@ export const StamphogRepoConfigsSyncInstallationCreateBody = /* @__PURE__ */ zod
),
})
.describe(
- "Request body for binding a completed GitHub App installation to the current team.\n\nRequires both the ``installation_id`` and the user-to-server OAuth ``code`` from the post-install\nredirect: the code proves the caller actually owns the installation, without which any caller could\nbind another org's installation to their own team."
+ "Request body for binding a GitHub App installation to the current team.\n\nAlways requires the user-to-server OAuth ``code`` (the ownership proof) and the ``state`` token.\n``installation_id`` is optional: when present (the fresh-install redirect) exactly that installation\nis verified and synced; when absent or blank (the authorize-first redirect) the caller's accessible\ninstallations are discovered server-side from the code, so the client never has to supply a\nforgeable id."
)
diff --git a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
index 101afb47a0c8..be11d4a8979d 100644
--- a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
+++ b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconGithub } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonInput, LemonSelect, LemonSwitch, LemonTable } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonInput, LemonSelect, LemonSwitch, LemonTable, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
@@ -19,18 +19,19 @@ export const scene: SceneExport = {
}
function ConnectRepositoryButton(): JSX.Element {
- const { installUrl, installInfoLoading } = useValues(stamphogSceneLogic)
+ // Authorize-first: the connect button opens the OAuth authorize URL. An already-installed user gets a
+ // silent instant redirect back, so it never dead-ends on GitHub's "update installation" screen.
+ const { authorizeUrl, installInfoLoading } = useValues(stamphogSceneLogic)
return (
<LemonButton
type="primary"
icon={<IconGithub />}
- to={installUrl || undefined}
- targetBlank
+ to={authorizeUrl || undefined}
disableClientSideRouting
disabledReason={
installInfoLoading
? 'Loading install details'
- : installUrl
+ : authorizeUrl
? undefined
: 'GitHub App not configured yet'
}
@@ -41,7 +42,54 @@ function ConnectRepositoryButton(): JSX.Element {
}
function SyncedBanner(): JSX.Element | null {
- const { syncedRepos, skippedRepos } = useValues(stamphogSceneLogic)
+ const { syncedRepos, skippedRepos, appNotInstalled, installUrl, discoveredInstallations } =
+ useValues(stamphogSceneLogic)
+ const { connectInstallation } = useActions(stamphogSceneLogic)
+
+ // Discovery found several installations and bound nothing: the user picks which one this team
+ // connects. The pick rides sessionStorage through one more (silent) authorize hop, and the
+ // backend's explicit-id path verifies it.
+ if (discoveredInstallations.length > 0) {
+ return (
+ <LemonBanner type="info">
+ <p className="font-medium">Stamphog is installed on several GitHub accounts</p>
+ <p>Pick the one to connect to this project:</p>
+ <div className="flex gap-2 flex-wrap">
+ {discoveredInstallations.map((installation) => (
+ <LemonButton
+ key={installation.id}
+ type="secondary"
+ icon={<IconGithub />}
+ onClick={() => connectInstallation(installation.id)}
+ >
+ {installation.account_login}
+ </LemonButton>
+ ))}
+ </div>
+ </LemonBanner>
+ )
+ }
+
+ // Discovery found no installation the user can reach: they authorized the App but never installed it
+ // on the org. Point them at the GitHub install page (install_url still carries a fresh state token).
+ if (appNotInstalled) {
+ return (
+ <LemonBanner type="warning">
+ <p className="font-medium">Stamphog isn't installed on GitHub yet</p>
+ <p>
+ Install the Stamphog GitHub App on your organization to connect its repositories.
+ {installUrl && (
+ <>
+ {' '}
+ <Link to={installUrl} target="_blank" disableClientSideRouting>
+ Install on GitHub
+ </Link>
+ </>
+ )}
+ </p>
+ </LemonBanner>
+ )
+ }
if (syncedRepos.length === 0 && skippedRepos.length === 0) {
return null
diff --git a/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts b/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts
index f4e884999236..4f40ee0bf0b5 100644
--- a/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts
+++ b/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts
@@ -14,14 +14,24 @@ import {
} from '../../generated/api'
import type {
ReviewModeEnumApi,
+ StamphogDiscoveredInstallationApi,
StamphogInstallInfoApi,
StamphogRepoConfigApi,
+ StamphogSyncInstallationRequestApi,
StamphogSyncInstallationResponseApi,
} from '../../generated/api.schemas'
+// Carries the user's installation pick across the authorize redirect: the OAuth code is single-use
+// and consumed server-side before installations are known, so the choice can't ride the request
+// that discovered them — it rides the browser instead, and the explicit-id path verifies it.
+const PENDING_INSTALLATION_STORAGE_KEY = 'stamphog-pending-installation-id'
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogSceneLogicValues {
currentProjectId: number | string // teamLogic
+ appNotInstalled: boolean
+ authorizeUrl: string
+ discoveredInstallations: readonly StamphogDiscoveredInstallationApi[]
filteredRepoConfigs: StamphogRepoConfigApi[]
installInfo: StamphogInstallInfoApi | null
installInfoLoading: boolean
@@ -38,6 +48,9 @@ export interface stamphogSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogSceneLogicActions {
+ connectInstallation: (installationId: string) => {
+ installationId: string
+ }
loadInstallInfo: () => any
loadInstallInfoFailure: (
error: string,
@@ -68,6 +81,9 @@ export interface stamphogSceneLogicActions {
repoConfigs: StamphogRepoConfigApi[]
payload?: any
}
+ redirectToAuthorize: () => {
+ value: true
+ }
repoUpdateDone: (id: string) => {
id: string
}
@@ -102,8 +118,18 @@ export interface stamphogSceneLogicActions {
id: string
triggerLabel: string
}
- syncInstallation: ({ installationId, code, state }: { code: string; installationId: string; state: string }) => {
- installationId: string
+ syncInstallation: ({
+ installationId,
+ code,
+ state,
+ }: {
+ code: string
+ // Optional: absent on the authorize-first redirect, where the backend discovers the
+ // caller's installations from the code instead of trusting a supplied id.
+ installationId?: string
+ state: string
+ }) => {
+ installationId?: string
code: string
state: string
}
@@ -117,14 +143,14 @@ export interface stamphogSceneLogicActions {
syncInstallationSuccess: (
syncResult: StamphogSyncInstallationResponseApi,
payload?: {
- installationId: string
+ installationId?: string
code: string
state: string
}
) => {
syncResult: StamphogSyncInstallationResponseApi
payload?: {
- installationId: string
+ installationId?: string
code: string
state: string
}
@@ -135,6 +161,11 @@ export interface stamphogSceneLogicActions {
export interface stamphogSceneLogicMeta {
__keaTypeGenInternalSelectorTypes: {
installUrl: (installInfo: StamphogInstallInfoApi | null) => string
+ authorizeUrl: (installInfo: StamphogInstallInfoApi | null) => string
+ appNotInstalled: (syncResult: StamphogSyncInstallationResponseApi | null) => boolean
+ discoveredInstallations: (
+ syncResult: StamphogSyncInstallationResponseApi | null
+ ) => readonly StamphogDiscoveredInstallationApi[]
syncedRepos: (syncResult: StamphogSyncInstallationResponseApi | null) => readonly StamphogRepoConfigApi[]
skippedRepos: (syncResult: StamphogSyncInstallationResponseApi | null) => readonly string[]
filteredRepoConfigs: (repoConfigs: StamphogRepoConfigApi[], repoSearch: string) => StamphogRepoConfigApi[]
@@ -162,6 +193,8 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([
setTriggerLabel: (id: string, triggerLabel: string) => ({ id, triggerLabel }),
repoUpdateDone: (id: string) => ({ id }),
setRepoSearch: (search: string) => ({ search }),
+ redirectToAuthorize: true,
+ connectInstallation: (installationId: string) => ({ installationId }),
}),
loaders(({ values }) => ({
@@ -207,15 +240,17 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([
code,
state,
}: {
- installationId: string
+ // Optional: absent on the authorize-first redirect, where the backend discovers the
+ // caller's installations from the code instead of trusting a supplied id.
+ installationId?: string
code: string
state: string
}) => {
- return stamphogRepoConfigsSyncInstallationCreate(String(values.currentProjectId), {
- installation_id: installationId,
- code,
- state,
- })
+ const body: StamphogSyncInstallationRequestApi = { code, state }
+ if (installationId) {
+ body.installation_id = installationId
+ }
+ return stamphogRepoConfigsSyncInstallationCreate(String(values.currentProjectId), body)
},
},
],
@@ -242,6 +277,21 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([
(s) => [s.installInfo],
(installInfo: StamphogInstallInfoApi | null): string => installInfo?.install_url ?? '',
],
+ authorizeUrl: [
+ (s) => [s.installInfo],
+ (installInfo: StamphogInstallInfoApi | null): string => installInfo?.authorize_url ?? '',
+ ],
+ appNotInstalled: [
+ (s) => [s.syncResult],
+ (syncResult: StamphogSyncInstallationResponseApi | null): boolean => syncResult?.app_not_installed ?? false,
+ ],
+ // Non-empty only when discovery found several installations and bound nothing: the user must
+ // pick which one this team connects (reachability is not intent).
+ discoveredInstallations: [
+ (s) => [s.syncResult],
+ (syncResult: StamphogSyncInstallationResponseApi | null): readonly StamphogDiscoveredInstallationApi[] =>
+ syncResult?.installations ?? [],
+ ],
syncedRepos: [
(s) => [s.syncResult],
(syncResult: StamphogSyncInstallationResponseApi | null): readonly StamphogRepoConfigApi[] =>
@@ -309,10 +359,35 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([
actions.repoUpdateDone(id)
}
},
- syncInstallationSuccess: () => {
- // Drop installation_id from the URL so a refresh doesn't re-sync,
+ connectInstallation: ({ installationId }) => {
+ sessionStorage.setItem(PENDING_INSTALLATION_STORAGE_KEY, installationId)
+ actions.redirectToAuthorize()
+ },
+ redirectToAuthorize: async () => {
+ // The setup_action=update redirect carries no code (nothing to sync), so bounce the browser
+ // through the authorize URL for one silent hop — GitHub redirects straight back with a code
+ // and the discovery path takes over. Fetch install info directly rather than racing the loader,
+ // which may not have resolved yet when the callback fires.
+ try {
+ const info = await stamphogRepoConfigsInstallInfoRetrieve(String(values.currentProjectId))
+ if (info.authorize_url) {
+ window.location.href = info.authorize_url
+ } else {
+ lemonToast.error('GitHub App is not configured, so it cannot be connected')
+ }
+ } catch {
+ lemonToast.error('Could not load GitHub connection details. Try again.')
+ }
+ },
+ syncInstallationSuccess: ({ syncResult }) => {
+ // Drop the callback params from the URL so a refresh doesn't re-sync,
// then refresh the list to show the newly bound repos.
router.actions.replace(urls.stamphog())
+ if (syncResult?.app_not_installed) {
+ // Discovery found no installation the user can reach — they still need to install the App.
+ // The banner and connect button surface the install link.
+ lemonToast.info("Stamphog isn't installed on GitHub yet. Use the install link to add it.")
+ }
actions.loadRepoConfigs()
},
syncInstallationFailure: () => {
@@ -322,18 +397,38 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([
urlToAction(({ actions }) => ({
[urls.stamphogCallback()]: (_, searchParams) => {
- // The GitHub setup redirect carries installation_id, a user OAuth code, and the state token
- // we minted in install_info. The backend needs the code to prove installation ownership and
- // the state to prove this callback belongs to the current team's own install flow.
- const installationId = searchParams.installation_id
+ // Two redirects land here, both carrying the state token we minted in install_info:
+ // - authorize/fresh-install: a user OAuth code (+ installation_id on a fresh install). The
+ // backend proves ownership from the code and discovers or verifies the installation.
+ // - setup_action=update (app already installed): installation_id + state but NO code. The id
+ // is user-editable and not trusted, so restart via authorize to obtain a real code.
+ // GitHub sends the user back with ?error=access_denied when they hit Cancel on the
+ // authorize screen — a normal action on the primary connect flow, not a failure. Land
+ // them back on the plain page instead of a silent dead-end on the callback URL.
+ if (searchParams.error) {
+ router.actions.replace(urls.stamphog())
+ if (searchParams.error === 'access_denied') {
+ lemonToast.info('GitHub authorization was cancelled.')
+ } else {
+ lemonToast.error('GitHub authorization failed. Try again.')
+ }
+ return
+ }
+ // A stashed pick (from the multi-installation chooser) fills in for the missing
+ // installation_id on the authorize redirect; an explicit URL param wins.
+ const stashedInstallationId = sessionStorage.getItem(PENDING_INSTALLATION_STORAGE_KEY)
+ sessionStorage.removeItem(PENDING_INSTALLATION_STORAGE_KEY)
+ const installationId = searchParams.installation_id || stashedInstallationId || undefined
const code = searchParams.code
const state = searchParams.state
- if (installationId && code && state) {
+ if (code && state) {
actions.syncInstallation({
- installationId: String(installationId),
+ installationId: installationId ? String(installationId) : undefined,
code: String(code),
state: String(state),
})
+ } else if (installationId && state) {
+ actions.redirectToAuthorize()
}
},
})),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 37a9ae8dcf95..2592fc8b16ef 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20308,7 +20308,7 @@ export namespace Schemas {
export interface DigestChannel {
readonly id: string;
/**
- * Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'.
+ * Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'. Immutable after creation — it anchors the audience and its opt-out tombstone.
* @maxLength 255
*/
audience_key: string;
@@ -43331,7 +43331,7 @@ export namespace Schemas {
export interface PatchedDigestChannel {
readonly id?: string;
/**
- * Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'.
+ * Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'. Immutable after creation — it anchors the audience and its opt-out tombstone.
* @maxLength 255
*/
audience_key?: string;
@@ -59828,26 +59828,40 @@ export namespace Schemas {
run: StaffWarmRun | null;
}
+ /**
+ * One installation of the App the authorizing user can reach, offered for an explicit pick.
+ */
+ export interface StamphogDiscoveredInstallation {
+ /** GitHub installation id, as a string. */
+ readonly id: string;
+ /** Login of the org or user account the installation lives on. */
+ readonly account_login: string;
+ }
+
/**
* Static info the frontend needs to render the 'Connect a repository' button.
*/
export interface StamphogInstallInfo {
/** URL-friendly slug of the dedicated Stamphog GitHub App, or blank if unconfigured. */
readonly app_slug: string;
- /** GitHub install URL (github.com/apps/<slug>/installations/new) the user opens to install the App, or blank if the App slug is unconfigured. */
+ /** GitHub install URL (github.com/apps/<slug>/installations/new) the user opens to install the App, or blank if the App slug is unconfigured. Used for the genuinely-not-installed case; the primary 'Connect' button uses authorize_url instead. */
readonly install_url: string;
+ /** GitHub authorize URL (github.com/login/oauth/authorize) the 'Connect' button opens. Authorize-first: an already-installed user is redirected straight back with an OAuth code (no installation_id), and sync_installation then discovers their installations server-side. Blank if the App client id is unconfigured. */
+ readonly authorize_url: string;
}
/**
- * Request body for binding a completed GitHub App installation to the current team.
+ * Request body for binding a GitHub App installation to the current team.
*
- * Requires both the ``installation_id`` and the user-to-server OAuth ``code`` from the post-install
- * redirect: the code proves the caller actually owns the installation, without which any caller could
- * bind another org's installation to their own team.
+ * Always requires the user-to-server OAuth ``code`` (the ownership proof) and the ``state`` token.
+ * ``installation_id`` is optional: when present (the fresh-install redirect) exactly that installation
+ * is verified and synced; when absent or blank (the authorize-first redirect) the caller's accessible
+ * installations are discovered server-side from the code, so the client never has to supply a
+ * forgeable id.
*/
export interface StamphogSyncInstallationRequest {
- /** GitHub App installation ID returned on the post-install Setup URL redirect. */
- installation_id: string;
+ /** GitHub App installation ID from the fresh-install Setup URL redirect. Optional: absent or blank means discover the caller's installations from the OAuth code instead (authorize-first flow). The id is not trusted on its own — ownership is always proven via the code. */
+ installation_id?: string;
/** GitHub user-to-server OAuth code from the post-install redirect (present when the App has 'Request user authorization during installation' enabled). Exchanged server-side to prove the caller owns the installation before its repos are bound. */
code: string;
/** Signed state token minted by install_info and round-tripped through GitHub's install redirect. Binds the callback to the team and user that started the flow, so a stolen installation_id + code can't be replayed against another team's session. */
@@ -59862,6 +59876,10 @@ export namespace Schemas {
readonly synced: readonly StamphogRepoConfig[];
/** Repository full names skipped because another team already owns them under this installation. */
readonly skipped: readonly string[];
+ /** True only on the discovery path (no installation_id) when the caller can reach no installation of this App — it isn't installed anywhere they can see. The frontend should route the user to the GitHub install page (install_url). Always false on the explicit installation_id path. */
+ readonly app_not_installed: boolean;
+ /** Populated only on the discovery path when the caller can reach MORE than one installation of this App: nothing was bound, and the user must pick which installation to connect. The frontend re-runs the authorize flow and calls back with the chosen installation_id, which the explicit path verifies. Empty whenever a bind happened (or nothing was found). */
+ readonly installations: readonly StamphogDiscoveredInstallation[];
}
/**
diff --git a/services/mcp/src/generated/stamphog/api.ts b/services/mcp/src/generated/stamphog/api.ts
index ade53c8fa0fc..eab829924bda 100644
--- a/services/mcp/src/generated/stamphog/api.ts
+++ b/services/mcp/src/generated/stamphog/api.ts
@@ -48,7 +48,9 @@ export const StamphogDigestChannelsCreateBody = /* @__PURE__ */ zod.object({
audience_key: zod
.string()
.max(stamphogDigestChannelsCreateBodyAudienceKeyMax)
- .describe("Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'."),
+ .describe(
+ "Opaque digest bucket this channel receives, e.g. 'repo:PostHog/posthog'. Immutable after creation — it anchors the audience and its opt-out tombstone."
+ ),
slack_integration_id: zod
.number()
.min(stamphogDigestChannelsCreateBodySlackIntegrationIdMin)
diff --git a/tools/pr-approval-agent/review_local.py b/tools/pr-approval-agent/review_local.py
index 4119bff9df0a..3483e4801765 100644
--- a/tools/pr-approval-agent/review_local.py
+++ b/tools/pr-approval-agent/review_local.py
@@ -61,6 +61,7 @@ from github import (
_git_diff_files,
_normalize_discussion_for_prompt,
_normalize_reviews_for_prompt,
+ _prompt_worthy_author,
_reaction_emoji,
is_bot_author,
)
@@ -114,10 +115,12 @@ def _build_pr_data(context: dict) -> PRData:
raw as the Action does) — so the prerequisite gate blocks on an active
CHANGES_REQUESTED, the agent sees maintainer discussion, and the migration
gate can see a passing "Migration risk" check. Inline review-thread comments
- (a GraphQL-only surface with thread-resolution state) and reactions are not
- carried, so they default empty — the reviewer prompt renders those sections
- as "none", which is strictly a subset of what the Action shows, never a
- fabrication.
+ (a GraphQL-only surface with thread-resolution state) are carried when the
+ hosted context supplies "review_threads"; only UNRESOLVED threads flow into
+ the prompt, since an unresolved inline "do not merge" is the blocker the
+ reviewer must see and resolved threads are noise. An absent key (the Action
+ runtime doesn't pass it) means an empty list — a clean no-op, never a crash.
+ Reactions on those inline comments are not carried, so they default empty.
"""
pr = context.get("pr") or {}
user = pr.get("user") or {}
@@ -128,11 +131,12 @@ def _build_pr_data(context: dict) -> PRData:
if not files:
files = [_convert_api_file(f) for f in context.get("files") or []]
- # Drop only EMPTY COMMENTED reviews from the offline reviews. The hosted context carries no
- # inline review-thread comments (review_comments=[]), so a bare COMMENTED state has no readable
- # feedback — yet _summarize_assurance would surface its author as a current-head reviewer
- # ("head_commented"), reading as independent assurance. Unseen feedback must reduce to "no
- # assurance," never a positive vouch. A COMMENTED review WITH a body is different: that text is
+ # Drop only EMPTY COMMENTED reviews from the offline reviews. A bare COMMENTED top-level review
+ # carries no readable body — yet _summarize_assurance would surface its author as a current-head
+ # reviewer ("head_commented"), reading as independent assurance. Unseen feedback must reduce to "no
+ # assurance," never a positive vouch. (Any inline feedback that review left still reaches the prompt
+ # via review_comments below, so dropping the empty top-level state loses nothing the reviewer needs.)
+ # A COMMENTED review WITH a body is different: that text is
# a maintainer's visible feedback (possibly a comment-only "hold"), and dropping it would let
# the reviewer approve without ever seeing it — it flows through, body and all.
reviews = [
@@ -149,6 +153,42 @@ def _build_pr_data(context: dict) -> PRData:
if (login := r.get("user") or "") and login.lower() in TRUSTED_REACTOR_BOTS and login != author_login
]
+ # Flatten the injected inline review threads into the review_comments shape the reviewer prompt
+ # consumes. Only UNRESOLVED threads reach the prompt (see _build_pr_data's docstring); the full
+ # list stays in the context. Each comment passes the same author-trust gate as reviews and
+ # discussion — an untrusted external commenter must not plant a fake maintainer hold, and
+ # stamphog's own prior comments must not feed back as third-party claims. Absent key -> empty, so
+ # the Action runtime (which doesn't pass it) is unaffected and the prompt renders no
+ # inline-comments section, exactly as before.
+ review_comments: list[dict] = []
+ for thread in context.get("review_threads") or []:
+ if thread.get("is_resolved"):
+ continue
+ for index, comment in enumerate(thread.get("comments") or []):
+ if not _prompt_worthy_author(
+ comment.get("author"), comment.get("author_association"), bool(comment.get("author_is_bot"))
+ ):
+ continue
+ # Real reply ids aren't carried in the lean shape; a truthy placeholder on the replies
+ # only marks reply-ness — the prompt's "(reply)" label and _summarize_assurance's
+ # "count threads (in_reply_to_id is None), not comments" semantic both key off it.
+ # Parity with the Action (github.py): only the TRUE thread root (index 0) may carry None.
+ # When the root is filtered (untrusted author, or stamphog's own finding), every survivor
+ # is a reply, so the thread contributes 0 to unresolved_threads — exactly like the Action,
+ # whose surviving replies keep their real non-None replyTo ids.
+ review_comments.append(
+ {
+ "user": comment.get("author") or "ghost",
+ "body": comment.get("body", ""),
+ "path": thread.get("path", ""),
+ "line": thread.get("line"),
+ "in_reply_to_id": None if index == 0 else -1,
+ "is_resolved": False,
+ "is_outdated": bool(thread.get("is_outdated")),
+ "reactions": [],
+ }
+ )
+
return PRData(
number=int(pr.get("number") or 0),
repo=context.get("repo") or "",
@@ -162,7 +202,7 @@ def _build_pr_data(context: dict) -> PRData:
head_sha=head_sha,
files=files,
reviews=_normalize_reviews_for_prompt(reviews, head_sha),
- review_comments=[],
+ review_comments=review_comments,
check_runs=context.get("check_runs") or [],
author_is_bot=is_bot_author(user),
pr_reactions=pr_reactions,
diff --git a/tools/pr-approval-agent/test_review_local.py b/tools/pr-approval-agent/test_review_local.py
index 48421c5c4a62..29f5d79f0ad2 100644
--- a/tools/pr-approval-agent/test_review_local.py
+++ b/tools/pr-approval-agent/test_review_local.py
@@ -3,6 +3,7 @@
import sys
from datetime import UTC, datetime
+import pytest
from unittest.mock import MagicMock
# review_local pulls in review_pr, whose reviewer.py imports claude_agent_sdk (installed by
@@ -72,6 +73,165 @@ def test_ownership_summary_preserves_individual_owners() -> None:
assert review_local._ownership_summary({"teams": [], "individuals": []}) == "no owned paths touched"
+def _thread_context(review_threads: list[dict]) -> dict:
+ return {
+ "repo": "PostHog/posthog",
+ "head_sha": "abc123",
+ "base_sha": "def456",
+ "pr": {"number": 1, "title": "t", "state": "OPEN", "user": {"login": "author", "type": "User"}},
+ "review_threads": review_threads,
+ }
+
+
+def _thread_comment(author: str, body: str, *, association: str = "MEMBER", is_bot: bool = False) -> dict:
+ return {"author": author, "author_association": association, "author_is_bot": is_bot, "body": body}
+
+
+def test_unresolved_review_threads_reach_the_prompt_and_resolved_are_dropped(monkeypatch) -> None:
+ # The hosted context now carries inline review threads. Only UNRESOLVED threads must flow into
+ # review_comments (which the reviewer prompt renders) — an unresolved inline "do not merge" is the
+ # blocker the reviewer must see; a resolved thread is settled noise that would dilute the signal.
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+ context = _thread_context(
+ [
+ {
+ "is_resolved": False,
+ "is_outdated": False,
+ "path": "posthog/api/insight.py",
+ "line": 42,
+ "comments": [_thread_comment("maintainer", "this is wrong, do not merge")],
+ },
+ {
+ "is_resolved": True,
+ "is_outdated": False,
+ "path": "posthog/api/other.py",
+ "line": 7,
+ "comments": [_thread_comment("maintainer", "was wrong, now fixed")],
+ },
+ ]
+ )
+
+ pr = review_local._build_pr_data(context)
+
+ assert [c["user"] for c in pr.review_comments] == ["maintainer"]
+ assert pr.review_comments[0]["body"] == "this is wrong, do not merge"
+ assert pr.review_comments[0]["path"] == "posthog/api/insight.py"
+ assert pr.review_comments[0]["line"] == 42
+ assert all("now fixed" not in c["body"] for c in pr.review_comments)
+
+
+ "author,association,is_bot,expect_kept",
+ [
+ pytest.param("alice", "MEMBER", False, True, id="trusted-member-kept"),
+ pytest.param("greptile-apps[bot]", "NONE", True, True, id="bot-reviewer-kept"),
+ # A drive-by external commenter must not reach the prompt: a fake maintainer hold is both
+ # griefable and forgeable — the same trust gate as reviews and discussion.
+ pytest.param("outsider", "NONE", False, False, id="untrusted-external-dropped"),
+ # Stamphog's own prior inline comments feed back as third-party claims about a stale
+ # snapshot — later runs suspect impersonation and refuse forever.
+ pytest.param("stamphog[bot]", "NONE", True, False, id="own-comment-dropped"),
+ ],
+)
+def test_review_thread_comments_pass_the_author_trust_gate(
+ monkeypatch, author: str, association: str, is_bot: bool, expect_kept: bool
+) -> None:
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+ context = _thread_context(
+ [
+ {
+ "is_resolved": False,
+ "is_outdated": False,
+ "path": "a.py",
+ "line": 1,
+ "comments": [_thread_comment(author, "a comment", association=association, is_bot=is_bot)],
+ }
+ ]
+ )
+
+ pr = review_local._build_pr_data(context)
+
+ assert ([c["user"] for c in pr.review_comments] == [author]) is expect_kept
+
+
+def test_multi_comment_thread_counts_as_one_unresolved_thread(monkeypatch) -> None:
+ # _summarize_assurance counts unresolved THREADS as comments with in_reply_to_id None — a single
+ # chatty 3-comment thread must read as one unresolved thread, not three. Only the true thread
+ # root (index 0) may carry in_reply_to_id None.
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+ context = _thread_context(
+ [
+ {
+ "is_resolved": False,
+ "is_outdated": False,
+ "path": "a.py",
+ "line": 1,
+ "comments": [
+ _thread_comment("alice", "root concern"),
+ _thread_comment("author", "pushed a fix"),
+ _thread_comment("alice", "still wrong"),
+ ],
+ }
+ ]
+ )
+
+ pr = review_local._build_pr_data(context)
+
+ assert len(pr.review_comments) == 3
+ assert [c["in_reply_to_id"] for c in pr.review_comments] == [None, -1, -1]
+
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ pipeline.pr = pr
+ assert pipeline._summarize_assurance()["unresolved_threads"] == 1
+
+
+def test_filtered_root_thread_counts_zero_unresolved_threads(monkeypatch) -> None:
+ # Parity with the Action: when the true thread root is filtered (untrusted author, or stamphog's
+ # own inline finding), the survivors are replies — the thread contributes 0 to unresolved_threads,
+ # exactly as the Action's real replyTo ids make it. Treating the first survivor as a root would
+ # make hosted stricter than the Action on every maintainer reply to a stamphog finding.
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+ context = _thread_context(
+ [
+ {
+ "is_resolved": False,
+ "is_outdated": False,
+ "path": "a.py",
+ "line": 1,
+ "comments": [
+ _thread_comment("rando", "drive-by root", association="NONE"),
+ _thread_comment("maintainer", "actually a fair point"),
+ ],
+ }
+ ]
+ )
+
+ pr = review_local._build_pr_data(context)
+
+ assert [c["user"] for c in pr.review_comments] == ["maintainer"]
+ assert pr.review_comments[0]["in_reply_to_id"] == -1
+
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ pipeline.pr = pr
+ assert pipeline._summarize_assurance()["unresolved_threads"] == 0
+
+
+def test_absent_review_threads_key_is_a_clean_no_op(monkeypatch) -> None:
+ # The Action runtime doesn't pass review_threads yet, so a context without the key must default to
+ # no inline comments rather than crash — the engine parity contract.
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+ context = {
+ "repo": "PostHog/posthog",
+ "head_sha": "abc123",
+ "base_sha": "def456",
+ "pr": {"number": 1, "title": "t", "state": "OPEN", "user": {"login": "author", "type": "User"}},
+ }
+
+ pr = review_local._build_pr_data(context)
+
+ assert pr.review_comments == []
+
+
def test_fresh_trusted_bot_eyes_reach_pr_data_and_flag_in_flight(monkeypatch) -> None:
# The hosted context now carries raw PR reactions; a fresh 👀 from an allowlisted reviewer bot
# must reach PRData so the offline WAIT check can fire — hard-coding pr_reactions=[] meant