Skip to content

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

feat(stamphog): request reviews and read reasoning through mcp (#104432)

Julian Bez8d503dcec222
diff --git a/.agents/skills/improving-mcp-tools/SKILL.md b/.agents/skills/improving-mcp-tools/SKILL.md
index b4ee9b7afa4a..6e1729e58951 100644
--- a/.agents/skills/improving-mcp-tools/SKILL.md
+++ b/.agents/skills/improving-mcp-tools/SKILL.md
@@ -58,7 +58,7 @@ POSTHOG_API_BASE_URL=http://localhost:8000 pnpm dev:hono`, personal API key as
5. **Ship.** One PR per iteration with before/after scores in the body (format
in [references/campaign-journal.md](references/campaign-journal.md)). Keep
it stampable: ≤400 changed lines, only files inside the allowlist below,
- apply the `stamphog` label. Autonomy level comes from the campaign config —
+ request a stamphog review (MCP first, label fallback, see `/merging-prs`). Autonomy level comes from the campaign config —
default is **draft PR for human review**; only arm auto-merge when the
operator has explicitly enabled the self-driving experiment (see
guardrails).
diff --git a/.agents/skills/merging-prs/SKILL.md b/.agents/skills/merging-prs/SKILL.md
index bb7871b18fbf..da24269fc67e 100644
--- a/.agents/skills/merging-prs/SKILL.md
+++ b/.agents/skills/merging-prs/SKILL.md
@@ -7,7 +7,8 @@ description: >
Trunk's own reason for the terminal transition. Use when asked to merge a PR,
"merge when ready", "land it", "ship it", to merge a whole stack (comment on
the top PR — the queue merges it and every layer below atomically), to get a
- PR approved via the `stamphog` label, or to babysit/watch a PR through the
+ PR approved by stamphog (MCP review request first, `stamphog` label as the
+ fallback), or to babysit/watch a PR through the
queue. Never use `gh pr merge` in this repo — the queue is the only path into
master.
---
@@ -20,7 +21,7 @@ To merge, you enqueue the PR with a comment, then watch it until Trunk lands it.
## Required user approval
-Before posting `/trunk merge`, invoking `trunk merge`, or re-enqueueing, obtain explicit user approval in the current conversation for the identified PR or stack. These actions can cause a PR to land. Never infer approval from a request to prepare a PR, move it toward merge, make it ready, resolve blockers, monitor it, or babysit it. You may inspect status, address reviews and CI, apply `stamphog` when approval is missing, and report that the PR is ready; then wait for a direct instruction to merge or enqueue it.
+Before posting `/trunk merge`, invoking `trunk merge`, or re-enqueueing, obtain explicit user approval in the current conversation for the identified PR or stack. These actions can cause a PR to land. Never infer approval from a request to prepare a PR, move it toward merge, make it ready, resolve blockers, monitor it, or babysit it. You may inspect status, address reviews and CI, request a stamphog review when approval is missing, and report that the PR is ready; then wait for a direct instruction to merge or enqueue it.
`<n>` below is the PR number.
Resolve the repo slug once if you need it: `REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)`.
@@ -36,7 +37,11 @@ gh pr view <n> --json state,isDraft,mergeable,reviewDecision,statusCheckRollup,b
- **Failing required checks** (`statusCheckRollup`) → the queue will just reject it. Report which checks are red and stop; fix them first. **Pending** checks are fine — the queue waits for them. To work out _why_ a check is red, use `/debugging-ci-failures`.
- **Merge conflicts** (`mergeable == "CONFLICTING"`) → report and stop; merge `master` in first.
- **Head is on a fork** (`isCrossRepository == true`) → backend CI ran on GitHub Actions, so the required check is on the head as usual. Depot's optional checks are absent; that is expected and needs no action.
-- **Missing approval** (`reviewDecision == "REVIEW_REQUIRED"`, or a stamphog approval was dismissed) → apply the `stamphog` label yourself: `gh pr edit <n> --add-label stamphog`. That triggers the automated review-and-approve flow ([the engine README](../../../products/stamphog/packages/pr-approval-agent/README.md)); on an `APPROVED` verdict the Stamphog app posts the approval that satisfies the required review. Re-applying the label is always safe and is the intended retry path — it gets stripped on a `REFUSED`/`ESCALATE` verdict, and after addressing that feedback you re-apply it to request a fresh review. Read the reason first: every verdict is its own review from the Stamphog app, opening with whether it approved. Re-applying the label without changing anything just repeats the same verdict. It stays sticky across ordinary pushes (non-trivial deltas re-review automatically), and it never works on bot-authored PRs.
+- **Missing approval** (`reviewDecision == "REVIEW_REQUIRED"`, or a stamphog approval was dismissed) → ask stamphog for a review. Stamphog is the automated review-and-approve flow ([the engine README](../../../products/stamphog/packages/pr-approval-agent/README.md)): on an `APPROVED` verdict the Stamphog app posts the approval that satisfies the required review. Use the MCP route first, and the label only when MCP is not available.
+ - **MCP (first choice).** Call the PostHog MCP tool `stamphog-review-runs-create` with `repository` (the `$REPO` slug) and `pr_number`. It returns the run at once, with status `queued`. Poll `stamphog-review-runs-get` with the run `id` until `status` is `completed`, `gated`, `failed`, or `superseded`. Read `verdict` and `reasoning` there, not on GitHub. `created: false` means a run already covers the current head, so do not request again until the head moves. A request covers one head: after you push, request again.
+ - **Refusals.** A `409 not_reviewable` means stamphog does not review this PR at all (a draft, closed, bot-authored, from outside the repo, or an author without write access). The message says which. The label cannot help there, so report it.
+ - **Label (fallback).** Use `gh pr edit <n> --add-label stamphog` when the MCP tool is not in your tool list, when the call fails on auth, or when it returns `404 not_found` (the repo is not connected in that PostHog project) or `503`. The label is sticky across ordinary pushes (non-trivial deltas re-review automatically), and it gets stripped on a `REFUSED`/`ESCALATE` verdict. Each verdict is its own review from the Stamphog app, opening with whether it approved.
+ - **Either route:** read the reason before you retry. A retry without a change repeats the same verdict. Stamphog never approves bot-authored PRs.
- **Part of a stack** (`baseRefName != "master"`, or the PR appears in `gh api repos/$REPO/stacks`) → the queue handles stacks natively: enqueueing a PR enqueues it **and every unmerged layer below it**, tests them together, and merges them atomically. After explicit user approval, comment `/trunk merge` on the **top** PR to merge the whole stack, or on the highest layer you want landed to merge just the bottom part. Run this preflight on every layer being merged, not only the one you comment on. `/stacking-prs` covers restack mechanics and the post-merge `gh stack sync --prune`.
## 2. Enqueue
diff --git a/.agents/skills/triaging-merge-queue-failures/SKILL.md b/.agents/skills/triaging-merge-queue-failures/SKILL.md
index b9a11fc8878a..dd661ffd57dd 100644
--- a/.agents/skills/triaging-merge-queue-failures/SKILL.md
+++ b/.agents/skills/triaging-merge-queue-failures/SKILL.md
@@ -204,7 +204,7 @@ This covers a push to the PR's own branch only. Trunk tearing down its own shado
`state=conflict` or `state=blocked`, or `mergeable_state` is `dirty`/`blocked`, or `draft` is true. A PR that is not mergeable is not admitted to the queue at all, so requeueing changes nothing.
-**Verdict: hold — fix the PR first.** Merge `master` in (or let the conflict autoresolver handle it), fix or wait for required checks, apply the `stamphog` label if approval is missing, then submit again.
+**Verdict: hold — fix the PR first.** Merge `master` in (or let the conflict autoresolver handle it), fix or wait for required checks, request a stamphog review if approval is missing (`/merging-prs` has the MCP-first route), then submit again.
### 3. Did a gate fail because its run was cancelled?
diff --git a/AGENTS.md b/AGENTS.md
index ca72b9eb502a..20f3fb92db0f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -104,7 +104,7 @@ Never run `gh pr merge` or click the GitHub merge button — both are blocked by
**Agents must not enqueue, merge, re-enqueue, or otherwise cause a PR to land without explicit user approval in the current conversation for the identified PR or stack.**
Do not infer that approval from requests to prepare a PR, move it toward merge, make it ready, monitor it, or resolve its blockers.
-Agents may inspect status, fix code and CI, apply the `stamphog` label when a required approval is missing, and report that a PR is ready — then wait for a direct instruction.
+Agents may inspect status, fix code and CI, request a stamphog review when a required approval is missing (MCP first, label fallback, see `/merging-prs`), and report that a PR is ready — then wait for a direct instruction.
Once approved, follow `/merging-prs` for the enqueue, watch and failure loop. It also covers why the PR's own checks never show queue progress.
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 07bbb9331fd1..984db60c479e 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -105,7 +105,7 @@ add a read-then-act path, pin it; this class of bug has been found on five separ
without a gateway. No `ANTHROPIC_API_KEY` may enter the sandbox environment.
- Egress is an explicit domain allowlist (`_sandbox_egress_allowlist`). Additions go through
`STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS`, not code edits.
-- Everything posted to GitHub goes through `_scrub_credentials` AND `_neutralize_active_markdown`
+- Everything posted to GitHub goes through `scrub_credentials` AND `neutralize_active_markdown` (`logic/scrubbing.py`)
(GitHub's camo proxy auto-fetches images — a markdown image URL is an exfiltration channel).
- The sandbox checkout is the PR head, so the engine's Agent SDK session runs with `setting_sources=[]` + `strict_mcp_config` (reviewer.py): a PR-shipped `.claude/settings.json` hook, `CLAUDE.md`, or `.mcp.json` is readable as untrusted content, never loaded as configuration.
Don't reintroduce filesystem settings discovery there.
@@ -171,6 +171,15 @@ narrow:
The condition is the derived `ReviewTrigger`, not the raw provenance flag, so it stays aligned with
what the reviewer prompt was told about its own invocation.
+## The manual trigger (the one exception to label mode)
+
+`request_manual_review` (`POST review_runs/` and the `stamphog-review-runs-create` MCP tool) queues a review because a project member asked for it.
+The request stands in for the trigger label, so it bypasses `review_mode` and nothing else.
+Every other webhook-path gate still refuses: closed PRs, drafts, bot authors, untrusted author associations, and authors below write permission.
+The requester's own GitHub access is not checked; the `stamphog:write` scope and the product's access control are the gate.
+The run is stamped `manual_review` provenance and the `manual` trigger, and it enters the workflow through `dismiss_stale_approvals` like every other run.
+A refusal writes nothing to GitHub and creates no run, so it cannot leave or remove an approval.
+
## Trust boundaries
- The review-gating fields (`enabled`, `review_mode`, `trigger_label`) and the soft-delete need the
@@ -204,6 +213,9 @@ narrow:
moment somebody adds the app.
- A declared channel that does not resolve is a dead end, never a retry with the audience slug —
the slug is the wrong name the declaration exists to correct.
+- Retrieving one review run returns the reviewer's parsed reasoning (`reasoning`, `showstoppers`, `review_body`, `change_summary`) to anyone who can read the run.
+ That is the text stamphog posts as its GitHub review, and it passes the same `scrub_credentials` and `neutralize_active_markdown` first.
+ The raw reviewer stdout, the PR payload, patches, and policy files never leave the facade.
- PR content — title, body, diff, comments, reactions — is untrusted input everywhere, including
in reviewer prompts and error messages persisted to API-readable fields (`run.error` keeps only
a truncated first line for exactly this reason).
diff --git a/products/stamphog/README.md b/products/stamphog/README.md
index ece9ef63e930..72ccb0224496 100644
--- a/products/stamphog/README.md
+++ b/products/stamphog/README.md
@@ -39,6 +39,11 @@ A transient failure must not silently drop labels across every queued PR.
Each run is stored as a `ReviewRun` row with its evidence bundle.
Runs are listed in the Stamphog runs page in the PostHog app (`/stamphog/runs`), and the same data is available through the stamphog API and its MCP tools (review runs, repo configs, digest runs).
+Retrieving one run also returns the reviewer's reasoning, the same text stamphog posts on GitHub.
+
+A project member can also ask for a review directly, by creating a review run (`POST review_runs/`, or the `stamphog-review-runs-create` MCP tool), and then poll the run for its verdict.
+The request replaces the trigger label, so it works in label mode.
+Every other rule still applies: drafts, closed PRs, bot-authored PRs, PRs from outside the repository, and PRs whose author lacks write access are refused.
## Connect a repository
diff --git a/products/stamphog/backend/facade/api.py b/products/stamphog/backend/facade/api.py
index 79dda729e508..3efd48e98bcd 100644
--- a/products/stamphog/backend/facade/api.py
+++ b/products/stamphog/backend/facade/api.py
@@ -19,6 +19,8 @@ from django.utils import timezone
import structlog
from ..logic.review_trigger import derive_review_trigger
+from ..logic.reviewer import parse_reviewer_output
+from ..logic.scrubbing import neutralize_active_markdown, scrub_credentials
from ..models import DigestRun, PullRequest, ReviewRun, StamphogRepoConfig
from . import contracts
from .enums import (
@@ -129,6 +131,8 @@ def _digest_run_to_dto(obj: DigestRun) -> contracts.DigestRunDTO:
# either omit the key or write a populated dict, so testing for the key and testing for truthiness
# agree — which is what lets the filter below stay in step with the derivation above it.
_SELF_DRIVING = Q(output__has_key="inbox_review")
+# Same shape for a manual request: request_manual_review writes a populated dict or no key at all.
+_MANUAL = Q(output__has_key="manual_review")
# Preserves the caller's queryset type, so a team-scoped queryset stays team-scoped through the filter.
_RunQS = TypeVar("_RunQS", bound=QuerySet)
@@ -139,6 +143,7 @@ def _derive_trigger(obj: ReviewRun) -> ReviewTrigger:
the reviewer invocation has to answer the same question before a run exists to read."""
return derive_review_trigger(
has_inbox_review=bool((obj.output or {}).get("inbox_review")),
+ has_manual_review=bool((obj.output or {}).get("manual_review")),
review_mode=obj.pull_request.repo_config.review_mode,
)
@@ -153,10 +158,12 @@ def _filter_by_trigger(qs: _RunQS, trigger: str) -> _RunQS:
"""
if trigger == ReviewTrigger.SELF_DRIVING:
return qs.filter(_SELF_DRIVING)
+ if trigger == ReviewTrigger.MANUAL:
+ return qs.exclude(_SELF_DRIVING).filter(_MANUAL)
if trigger == ReviewTrigger.LABEL:
- return qs.exclude(_SELF_DRIVING).filter(pull_request__repo_config__review_mode=ReviewMode.LABEL)
+ return qs.exclude(_SELF_DRIVING | _MANUAL).filter(pull_request__repo_config__review_mode=ReviewMode.LABEL)
if trigger == ReviewTrigger.ALL:
- return qs.exclude(_SELF_DRIVING).filter(pull_request__repo_config__review_mode=ReviewMode.ALL)
+ return qs.exclude(_SELF_DRIVING | _MANUAL).filter(pull_request__repo_config__review_mode=ReviewMode.ALL)
return qs.none()
@@ -230,6 +237,35 @@ def get_review_run(team_id: int, review_run_id: str) -> contracts.ReviewRunDTO |
return _review_run_to_dto(obj) if obj is not None else None
+def _clean_reviewer_text(text: str) -> str:
+ # The same redaction the posted GitHub review gets. An MCP client can render this as markdown,
+ # which fetches images on render the way GitHub's camo proxy does.
+ return neutralize_active_markdown(scrub_credentials(text))
+
+
+def get_review_reasoning(run: contracts.ReviewRunDTO) -> contracts.ReviewReasoningDTO:
+ """The reviewer's reasoning for a run, parsed from its stored output.
+
+ This is the text stamphog posts as its GitHub review. The raw reviewer stdout it is parsed
+ from never leaves the facade. All fields are None until the reviewer has run.
+ """
+ raw = (run.output or {}).get("reviewer_raw")
+ if not isinstance(raw, str) or not raw:
+ return contracts.ReviewReasoningDTO()
+ try:
+ parsed = parse_reviewer_output(raw)
+ except (AttributeError, TypeError, ValueError):
+ # A crashed or version-skewed engine can print a malformed verdict. Retrieve must still answer.
+ logger.warning("stamphog_review_reasoning_unparseable", review_run_id=str(run.id))
+ return contracts.ReviewReasoningDTO()
+ return contracts.ReviewReasoningDTO(
+ reasoning=_clean_reviewer_text(parsed.reasoning),
+ showstoppers=[_clean_reviewer_text(item) for item in parsed.showstoppers],
+ review_body=_clean_reviewer_text(parsed.review_body),
+ change_summary=_clean_reviewer_text(parsed.change_summary),
+ )
+
+
def create_review_run(
*,
team_id: int,
diff --git a/products/stamphog/backend/facade/contracts.py b/products/stamphog/backend/facade/contracts.py
index d4f5545989f7..c57f950d1af4 100644
--- a/products/stamphog/backend/facade/contracts.py
+++ b/products/stamphog/backend/facade/contracts.py
@@ -16,7 +16,14 @@ from uuid import UUID
from pydantic import Field
from pydantic.dataclasses import dataclass
-from .enums import ChannelResolutionSource, DigestRunStatus, ReviewRunStatus, ReviewTrigger, ReviewVerdict
+from .enums import (
+ ChannelResolutionSource,
+ DigestRunStatus,
+ ReviewRequestRefusal,
+ ReviewRunStatus,
+ ReviewTrigger,
+ ReviewVerdict,
+)
@dataclass(frozen=True)
@@ -111,6 +118,34 @@ class ReviewRunDTO:
completed_at: datetime | None = None
+@dataclass(frozen=True)
+class ReviewRequestResultDTO:
+ """The run a manual review request points at, and whether the request created it."""
+
+ run: ReviewRunDTO
+ # False when a live or delivered run already covered the PR's current head.
+ created: bool
+
+
+@dataclass(frozen=True)
+class ReviewReasoningDTO:
+ """The reviewer's reasoning for one run, all None until the reviewer has run."""
+
+ reasoning: str | None = None
+ showstoppers: list[str] | None = None
+ review_body: str | None = None
+ change_summary: str | None = None
+
+
+class ReviewRequestRefusedError(Exception):
+ """A manual review request did not queue a run. ``message`` is written for the requester."""
+
+ def __init__(self, refusal: ReviewRequestRefusal, message: str) -> None:
+ super().__init__(message)
+ self.refusal = refusal
+ self.message = message
+
+
class RepoAlreadyClaimedError(Exception):
"""Another team already owns this repository under this GitHub installation."""
diff --git a/products/stamphog/backend/facade/enums.py b/products/stamphog/backend/facade/enums.py
index bd993237908a..76bb84973572 100644
--- a/products/stamphog/backend/facade/enums.py
+++ b/products/stamphog/backend/facade/enums.py
@@ -36,19 +36,29 @@ TERMINAL_STATUSES = frozenset(
class ReviewTrigger(StrEnum):
"""What caused a run to exist, derived from the run and its repo config.
- Not stored: a run records `inbox_review` provenance on its output and inherits the repo's
- review_mode, and this collapses the two into the one answer a reader wants — why did stamphog
- look at this PR at all.
+ Not stored: a run records `inbox_review` or `manual_review` provenance on its output and
+ inherits the repo's review_mode, and this collapses them into the one answer a reader wants —
+ why did stamphog look at this PR at all.
"""
# Self-driving: stamphog reviewed a bot-authored PR off its own inbox provenance.
SELF_DRIVING = "self_driving"
+ # A project member asked for this review through the API.
+ MANUAL = "manual"
# The repo is in LABEL mode, so the trigger label opted this PR in.
LABEL = "label"
# The repo reviews every relevant PR event.
ALL = "all"
+class ReviewRequestRefusal(StrEnum):
+ """Why a manual review request did not queue a run. The message carries the specific reason."""
+
+ NOT_FOUND = "not_found"
+ NOT_REVIEWABLE = "not_reviewable"
+ GITHUB_UNAVAILABLE = "github_unavailable"
+
+
class ReviewVerdict(StrEnum):
NONE = "none"
APPROVED = "approved"
diff --git a/products/stamphog/backend/facade/review_requests.py b/products/stamphog/backend/facade/review_requests.py
new file mode 100644
index 000000000000..8a1fac9c4240
--- /dev/null
+++ b/products/stamphog/backend/facade/review_requests.py
@@ -0,0 +1,24 @@
+"""Facade for asking stamphog to review one pull request on a PostHog user's behalf.
+
+Lives apart from ``api.py`` for the same reason ``tasks.py`` and ``github.py`` do: this path pulls
+the GitHub client and the Celery task module, which must stay off the module review_hog's settings
+serializer imports on every request.
+"""
+
+from products.stamphog.backend.facade import contracts
+from products.stamphog.backend.facade.api import _review_run_to_dto
+from products.stamphog.backend.tasks.tasks import request_manual_review
+
+__all__ = ["request_review"]
+
+
+def request_review(
+ team_id: int, *, user_id: int | None, repository: str, pr_number: int
+) -> contracts.ReviewRequestResultDTO:
+ """Queue a stamphog review of a PR, or return the run already covering its current head.
+
+ Raises ``contracts.ReviewRequestRefusedError`` when the request is refused. The review itself
+ runs asynchronously, and whether it approves is stamphog's decision.
+ """
+ queued = request_manual_review(team_id, user_id, repository, pr_number)
+ return contracts.ReviewRequestResultDTO(run=_review_run_to_dto(queued.run), created=queued.created)
diff --git a/products/stamphog/backend/logic/review_trigger.py b/products/stamphog/backend/logic/review_trigger.py
index 8dc353aeb2f4..902222e4c637 100644
--- a/products/stamphog/backend/logic/review_trigger.py
+++ b/products/stamphog/backend/logic/review_trigger.py
@@ -12,14 +12,19 @@ from typing import Any
from ..facade.enums import ReviewMode, ReviewTrigger
-def derive_review_trigger(*, has_inbox_review: bool, review_mode: ReviewMode | str) -> ReviewTrigger:
- """Inbox provenance outranks the repo mode.
+def derive_review_trigger(
+ *, has_inbox_review: bool, review_mode: ReviewMode | str, has_manual_review: bool = False
+) -> ReviewTrigger:
+ """Inbox provenance outranks a manual request, and both outrank the repo mode.
A self-driving run is dispatched from the inbox whether or not the repo also reviews every PR
- event, so a repo in ALL mode still reports SELF_DRIVING for those PRs.
+ event, so a repo in ALL mode still reports SELF_DRIVING for those PRs. A manual request is an
+ explicit ask, so it reports MANUAL in either mode.
"""
if has_inbox_review:
return ReviewTrigger.SELF_DRIVING
+ if has_manual_review:
+ return ReviewTrigger.MANUAL
if review_mode == ReviewMode.LABEL:
return ReviewTrigger.LABEL
return ReviewTrigger.ALL
@@ -41,5 +46,7 @@ def trigger_for_run(*, output: dict[str, Any] | None, review_mode: ReviewMode |
if stamped:
return str(stamped)
return derive_review_trigger(
- has_inbox_review=bool((output or {}).get("inbox_review")), review_mode=review_mode
+ has_inbox_review=bool((output or {}).get("inbox_review")),
+ has_manual_review=bool((output or {}).get("manual_review")),
+ review_mode=review_mode,
).value
diff --git a/products/stamphog/backend/logic/scrubbing.py b/products/stamphog/backend/logic/scrubbing.py
new file mode 100644
index 000000000000..ab08f3c7bd9e
--- /dev/null
+++ b/products/stamphog/backend/logic/scrubbing.py
@@ -0,0 +1,61 @@
+"""Redaction applied to reviewer output before it leaves the product.
+
+The reviewer runs an LLM over untrusted PR content, so its text can carry credentials or
+auto-fetched markdown. Every surface that shows that text (GitHub reviews, the API) runs it
+through these first.
+"""
+
+import os
+import re
+
+
+def llm_env_secrets() -> list[str]:
+ """Non-empty LLM credential values in the worker env, gathered for output scrubbing.
+
+ These reach the sandbox via ``_reviewer_environment``; a confused or compromised
+ reviewer could echo them into stdout or the verdict. Redacting them server-side,
+ independent of model behavior, is what keeps a leaked key out of the PR and the DB.
+ POSTHOG_API_KEY is a public write token (spam-only blast radius) — scrubbed for tidiness.
+ """
+ return [
+ value
+ for key in ("AI_GATEWAY_API_KEY", "ANTHROPIC_API_KEY", "AI_GATEWAY_URL", "POSTHOG_API_KEY")
+ if (value := os.environ.get(key))
+ ]
+
+
+# Inline markdown images and raw <img> tags in text GitHub renders — both are removed outright,
+# URL included. Reference-style image forms are handled by the ``![`` demotion below.
+_MARKDOWN_IMAGE_RE = re.compile(r"!\[[^\]]*\]\([^)]*\)|<img\b[^>]*>", re.IGNORECASE)
+
+
+def neutralize_active_markdown(text: str) -> str:
+ """Remove auto-fetched markdown constructs from reviewer-authored text before it reaches GitHub.
+
+ The reviewer LLM reads untrusted PR content, so its output can be prompt-injected. Credential
+ scrubbing is exact-string only — a token re-encoded (base64, split) into an image URL slips
+ through, and GitHub fetching the image on render (through its camo proxy, no click needed) would
+ exfiltrate it OUTSIDE the sandbox egress allowlist.
+
+ Inline images and <img> tags are removed URL-and-all. Every OTHER markdown image form —
+ reference ``![a][ref]``, collapsed, shortcut — starts with ``![``, so the trailing demotion to
+ ``[`` turns anything left into a plain link, which GitHub never fetches without a click.
+ Deliberately a syntax demotion rather than an enumeration of forms: an image form this function's
+ author didn't think of still gets demoted. Plain links stay clickable, so legitimate references
+ to code and PRs survive.
+ """
+ return _MARKDOWN_IMAGE_RE.sub("[image removed]", text).replace("![", "[")
+
+
+def scrub_credentials(text: str, *secrets: str) -> str:
+ """Redact credential material before it reaches ``ReviewRun``, the logs, or GitHub.
+
+ Scrubs the passed GitHub token / basic-auth material plus any LLM credentials present
+ in the worker env — deterministic, so it does not depend on what the reviewer emits.
+ """
+ for secret in secrets:
+ if secret:
+ text = text.replace(secret, "***")
+ for secret in llm_env_secrets():
+ text = text.replace(secret, "[redacted]")
+ return text
diff --git a/products/stamphog/backend/presentation/serializers.py b/products/stamphog/backend/presentation/serializers.py
index e4d81b0bdc1b..7ee1a0a0a81e 100644
--- a/products/stamphog/backend/presentation/serializers.py
+++ b/products/stamphog/backend/presentation/serializers.py
@@ -48,8 +48,8 @@ class _ReviewOutputSummarySerializer(serializers.Serializer):
"""Allowlisted, non-sensitive slice of ``ReviewRun.output``.
The raw ``output`` blob also holds the reviewer's stdout, the full PR payload, changed-file patches,
- and default-branch policy file contents — repository content a project member without repo access
- must never read. Only these derived, content-free fields are exposed.
+ and default-branch policy file contents, none of which the API returns. The reviewer's reasoning,
+ the text stamphog posts on GitHub, is parsed out of the stdout and returned as ``reasoning``.
"""
stamphog_version = serializers.CharField(
@@ -329,6 +329,28 @@ class PullRequestSerializer(DataclassSerializer):
return obj.merged_at is not None
+class _ReviewReasoningSerializer(serializers.Serializer):
+ """The reviewer's reasoning for one run, the same text stamphog posts as its GitHub review."""
+
+ reasoning = serializers.CharField(
+ read_only=True, allow_null=True, help_text="The reviewer's explanation of its verdict."
+ )
+ showstoppers = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ allow_null=True,
+ help_text="Issues the reviewer found that block approval.",
+ )
+ review_body = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="The review text stamphog posts on GitHub: the reasoning, the judgment points, and the gate outcome.",
+ )
+ change_summary = serializers.CharField(
+ read_only=True, allow_null=True, help_text="A plain-language summary of what the change does."
+ )
+
+
@extend_schema_serializer(component_name="ReviewRun")
class ReviewRunSerializer(DataclassSerializer):
pull_request = serializers.UUIDField(
@@ -363,7 +385,7 @@ class ReviewRunSerializer(DataclassSerializer):
trigger = serializers.ChoiceField(
choices=[(t.value, t.name) for t in ReviewTrigger],
read_only=True,
- help_text="What caused this run to exist: self-driving inbox provenance, the repo's trigger label, or the repo reviewing every PR event.",
+ help_text="What caused this run to exist: self-driving inbox provenance, a manual request through the API, the repo's trigger label, or the repo reviewing every PR event.",
)
status = serializers.ChoiceField(
choices=[(s.value, s.name) for s in ReviewRunStatus],
@@ -409,13 +431,25 @@ class ReviewRunSerializer(DataclassSerializer):
)
output = serializers.SerializerMethodField(
help_text=(
- "Allowlisted, non-sensitive subset of the reviewer output blob (stamphog version, reviewer "
- "exit code). The raw reviewer stdout, PR payload, changed-file patches, and policy file "
- "contents are deliberately excluded — they carry repository content a project member without "
- "repo access must not read."
+ "Allowlisted subset of the reviewer output blob (stamphog version, reviewer exit code). The raw "
+ "reviewer stdout, PR payload, changed-file patches, and policy file contents are excluded. "
+ "The reviewer's reasoning, the text stamphog posts on GitHub, is in `reasoning` instead."
+ ),
+ )
+
+ reasoning = serializers.SerializerMethodField(
+ help_text=(
+ "The reviewer's reasoning, the same text stamphog posts as its GitHub review. Returned only when "
+ "retrieving a single run, and null in list results. Its fields are null until the reviewer has run."
),
)
+ @extend_schema_field(_ReviewReasoningSerializer(allow_null=True))
+ def get_reasoning(self, _obj: contracts.ReviewRunDTO) -> dict[str, object] | None:
+ # The view puts the parsed reasoning in the context on retrieve only, so list pages stay small.
+ reasoning = self.context.get("reasoning")
+ return _ReviewReasoningSerializer(reasoning).data if reasoning is not None else None
+
@extend_schema_field(_ReviewOutputSummarySerializer)
def get_output(self, obj: contracts.ReviewRunDTO) -> dict[str, object]:
# Explicit allowlist: never echo reviewer_raw / pr / files / policy_files out of the API.
@@ -457,6 +491,7 @@ class ReviewRunSerializer(DataclassSerializer):
"verdict",
"gate_result",
"output",
+ "reasoning",
"error",
"posted_review_id",
"verdict_posted_at",
@@ -476,6 +511,34 @@ class ReviewRunSerializer(DataclassSerializer):
}
+class ReviewRequestSerializer(serializers.Serializer):
+ """Request body for asking stamphog to review one pull request."""
+
+ repository = serializers.CharField(
+ help_text="Full name of the GitHub repository, e.g. 'PostHog/posthog'. It must be connected and enabled in Stamphog."
+ )
+ pr_number = serializers.IntegerField(min_value=1, help_text="Pull request number on GitHub.")
+
+
+class ReviewRequestResponseSerializer(serializers.Serializer):
+ """The review run a request points at."""
+
+ run = ReviewRunSerializer(
+ read_only=True,
+ help_text=(
+ "The review run for the pull request's current head. Poll it by id until status is terminal "
+ "(completed, gated, failed, or superseded)."
+ ),
+ )
+ created = serializers.BooleanField(
+ read_only=True,
+ help_text=(
+ "True when this request queued a new run. False when a queued, running, or finished run already "
+ "covered the current head, which is returned instead."
+ ),
+ )
+
+
@extend_schema_serializer(component_name="DigestRun")
class DigestRunSerializer(DataclassSerializer):
status = serializers.ChoiceField(
diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.py
index d1f238d46609..e54f718415ef 100644
--- a/products/stamphog/backend/presentation/views.py
+++ b/products/stamphog/backend/presentation/views.py
@@ -17,7 +17,7 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.exceptions import APIException, NotFound, PermissionDenied, ValidationError
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
@@ -37,8 +37,9 @@ from products.stamphog.backend.facade import (
api as facade_api,
contracts,
)
-from products.stamphog.backend.facade.enums import ReviewTrigger
+from products.stamphog.backend.facade.enums import ReviewRequestRefusal, ReviewTrigger
+from ..facade import review_requests
from ..facade.github import (
StamphogGitHubError,
exchange_oauth_code_for_user_token,
@@ -49,6 +50,8 @@ from ..facade.github import (
from .serializers import (
DigestRunSerializer,
PullRequestSerializer,
+ ReviewRequestResponseSerializer,
+ ReviewRequestSerializer,
ReviewRunSerializer,
StamphogInstallInfoSerializer,
StamphogRepoConfigSerializer,
@@ -439,8 +442,23 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
return Response(data)
+_REFUSAL_STATUS = {
+ ReviewRequestRefusal.NOT_FOUND: 404,
+ ReviewRequestRefusal.NOT_REVIEWABLE: 409,
+ ReviewRequestRefusal.GITHUB_UNAVAILABLE: 503,
+}
+
+
+class ReviewRequestRefused(APIException):
+ """A refused review request, carrying the refusal as the error code so clients can branch on it."""
+
+ def __init__(self, error: contracts.ReviewRequestRefusedError) -> None:
+ super().__init__(detail=error.message, code=error.refusal.value)
+ self.status_code = _REFUSAL_STATUS[error.refusal]
+
+
class ReviewRunViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewSet):
- """Read-only history of stamphog review runs, filterable by repository, PR number, and status."""
+ """History of stamphog review runs, filterable by repository, PR number, and status, plus manual review requests."""
scope_object = "stamphog"
serializer_class = ReviewRunSerializer
@@ -467,7 +485,26 @@ class ReviewRunViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewSet):
run = facade_api.get_review_run(self.canonical_team_id, str(pk))
if run is None:
raise NotFound()
- return Response(self.get_serializer(run).data)
+ context = {**self.get_serializer_context(), "reasoning": facade_api.get_review_reasoning(run)}
+ return Response(ReviewRunSerializer(run, context=context).data)
+
+ @extend_schema(
+ request=ReviewRequestSerializer,
+ responses={200: ReviewRequestResponseSerializer, 201: ReviewRequestResponseSerializer},
+ )
+ def create(self, request: Request, **kwargs) -> Response:
+ serializer = ReviewRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ try:
+ result = review_requests.request_review(
+ self.canonical_team_id,
+ user_id=request.user.pk,
+ repository=serializer.validated_data["repository"],
+ pr_number=serializer.validated_data["pr_number"],
+ )
+ except contracts.ReviewRequestRefusedError as error:
+ raise ReviewRequestRefused(error)
+ return Response(ReviewRequestResponseSerializer(result).data, status=201 if result.created else 200)
@extend_schema(
parameters=[
@@ -498,7 +535,7 @@ class ReviewRunViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewSet):
OpenApiParameter.QUERY,
required=False,
enum=[t.value for t in ReviewTrigger],
- description="Filter by what caused the run: self_driving, label, or all.",
+ description="Filter by what caused the run: self_driving, manual, label, or all.",
),
],
responses={200: ReviewRunSerializer(many=True)},
diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.py
index dae542262e4b..ae1c06cc275d 100644
--- a/products/stamphog/backend/tasks/tasks.py
+++ b/products/stamphog/backend/tasks/tasks.py
@@ -16,9 +16,11 @@ from django.db.models import Q
from django.utils import timezone
from django.utils.dateparse import parse_datetime
+import requests
import structlog
from celery import shared_task
+from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubRateLimitError
from posthog.models.instance_setting import get_instance_setting
@@ -29,9 +31,11 @@ from products.stamphog.backend.activity_logging import (
log_repo_configs_disabled_by_webhook,
suppress_created_activity,
)
+from products.stamphog.backend.facade.contracts import ReviewRequestRefusedError, StamphogGitHubError
from products.stamphog.backend.facade.enums import (
TERMINAL_STATUSES,
ReviewMode,
+ ReviewRequestRefusal,
ReviewRunStatus,
ReviewTrigger,
ReviewVerdict,
@@ -1403,6 +1407,98 @@ def process_pull_request_event(payload: dict[str, Any], delivery_id: str) -> Non
_mark_pr_event_processed(delivery_id)
+def _reviewable_repo_config(team_id: int, repository: str) -> StamphogRepoConfig | None:
+ """The team's enabled config for ``repository`` that was bound through the verified sync flow.
+
+ Writer-pinned like every read that gates run creation (reader-lag invariant). Matched
+ case-insensitively because callers pass repository names in whatever casing they hold, while
+ configs keep GitHub's casing.
+ """
+ return (
+ StamphogRepoConfig.objects.for_team(team_id)
+ .using(router.db_for_write(StamphogRepoConfig))
+ .filter(provider="github", repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False)
+ .exclude(installation_id="")
+ .order_by("created_at", "id")
+ .first()
+ )
+
+
+def _reviewed_base_ref(run: ReviewRun) -> str:
+ """The base branch the run reviewed against, or "" before the workflow recorded the PR."""
+ reviewed_pr = (run.output or {}).get("pr") or {}
+ return (reviewed_pr.get("base") or {}).get("ref") or ""
+
+
+@frozen
+class _HeadQueueResult:
+ """What ``_queue_review_at_head`` did for one PR head."""
+
+ # None when a newer PR snapshot already committed, so this caller's head is stale.
+ run: ReviewRun | None
+ created: bool
+
+
+def _queue_review_at_head(
+ repo_config: StamphogRepoConfig, pr: dict[str, Any], head_sha: str, *, output: dict[str, Any]
+) -> _HeadQueueResult:
+ """Create a QUEUED run for the PR's current head, or return the run that already covers it.
+
+ Shared by the entries that fetch the PR from GitHub themselves rather than receive a webhook
+ payload. Same transaction and on_commit shape as ``process_pull_request_event``. A live or
+ delivered run at this head is returned as is, and a QUEUED one lost its workflow start, so its
+ workflow restarts on commit. Otherwise older live runs are superseded and a fresh run starts
+ once the row commits. Errors propagate so the caller can retry or report them.
+ """
+ team_id = repo_config.team_id
+ run_write_db = router.db_for_write(ReviewRun)
+ with transaction.atomic(using=run_write_db):
+ pr_obj = _upsert_pull_request(repo_config, pr)
+ # This fetch raced a push and a newer webhook snapshot already committed, so superseding
+ # its run for this older head would cancel the up-to-date review.
+ incoming_updated_at = parse_datetime(pr.get("updated_at") or "")
+ if (
+ incoming_updated_at is not None
+ and pr_obj.payload_updated_at is not None
+ and pr_obj.payload_updated_at > incoming_updated_at
+ ):
+ return _HeadQueueResult(run=None, created=False)
+ # Dedupe repeat requests against the current head; the row lock serializes races.
+ existing = (
+ ReviewRun.objects.for_team(team_id)
+ .using(run_write_db)
+ .select_for_update()
+ .filter(pull_request=pr_obj, head_sha=head_sha)
+ .exclude(status__in=(ReviewRunStatus.SUPERSEDED, ReviewRunStatus.FAILED))
+ .order_by("-created_at")
+ .first()
+ )
+ # A retarget changes the diff without moving the head, and in label mode no webhook run
+ # replaces the old verdict. A run that reviewed another base branch does not cover this one.
+ reviewed_base_ref = _reviewed_base_ref(existing) if existing is not None else ""
+ if reviewed_base_ref and reviewed_base_ref != (pr.get("base") or {}).get("ref"):
+ existing = None
+ if existing is not None:
+ if existing.status == ReviewRunStatus.QUEUED:
+ existing_run_id = str(existing.id)
+ transaction.on_commit(lambda: _start_review_workflow(existing_run_id, team_id), using=run_write_db)
+ return _HeadQueueResult(run=existing, created=False)
+ _supersede_prior_runs(pr_obj)
+ review_run = ReviewRun.objects.for_team(team_id).create(
+ team_id=team_id,
+ pull_request=pr_obj,
+ head_sha=head_sha,
+ delivery_id=None,
+ status=ReviewRunStatus.QUEUED,
+ output=output,
+ )
+ review_run_id = str(review_run.id)
+ # A post-commit start failure propagates to the caller. A retry re-enters through the
+ # dedupe above and restarts the still-QUEUED run.
+ transaction.on_commit(lambda: _start_review_workflow(review_run_id, team_id), using=run_write_db)
+ return _HeadQueueResult(run=review_run, created=True)
+
+
@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)
def process_inbox_pr_review(
team_id: int, pr_url: str, repository: str, acting_user_id: int, signal_report_id: str, task_run_id: str
@@ -1446,18 +1542,9 @@ def process_inbox_pr_review(
)
return
- # Writer-pinned like every read that gates run creation (reader-lag invariant); iexact because
- # tasks stores repository slugs lowercased while configs keep GitHub's casing.
- write_db = router.db_for_write(StamphogRepoConfig)
+ # iexact because tasks stores repository slugs lowercased while configs keep GitHub's casing.
try:
- repo_config = (
- StamphogRepoConfig.objects.for_team(team_id)
- .using(write_db)
- .filter(provider="github", repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False)
- .exclude(installation_id="")
- .order_by("created_at", "id")
- .first()
- )
+ repo_config = _reviewable_repo_config(team_id, repository)
except Exception as e:
logger.exception("stamphog_inbox_pr_config_resolution_failed", team_id=team_id, error=str(e))
raise cast(Any, process_inbox_pr_review).retry(exc=e)
@@ -1524,65 +1611,130 @@ def process_inbox_pr_review(
"task_run_id": str(linked.run_id),
"acting_user_id": acting_reviewer_id,
}
- # Same transaction/on_commit shape as the webhook path (see process_pull_request_event).
- run_write_db = router.db_for_write(ReviewRun)
try:
- with transaction.atomic(using=run_write_db):
- pr_obj = _upsert_pull_request(repo_config, pr)
- # This fetch raced a push and a newer webhook snapshot already committed, so superseding
- # its run for this older head would cancel the up-to-date review.
- incoming_updated_at = parse_datetime(pr.get("updated_at") or "")
- if (
- incoming_updated_at is not None
- and pr_obj.payload_updated_at is not None
- and pr_obj.payload_updated_at > incoming_updated_at
- ):
- logger.info("stamphog_inbox_pr_stale_snapshot", repository=repository, pr_number=pr_number)
- return
- # Dedupe repeat fires against the current head; the row lock serializes races. A live or
- # delivered run is already handled; a QUEUED one lost its workflow start, so restart it.
- existing = (
- ReviewRun.objects.for_team(team_id)
- .using(run_write_db)
- .select_for_update()
- .filter(pull_request=pr_obj, head_sha=head_sha)
- .exclude(status__in=(ReviewRunStatus.SUPERSEDED, ReviewRunStatus.FAILED))
- .order_by("-created_at")
- .first()
- )
- if existing is not None:
- if existing.status == ReviewRunStatus.QUEUED:
- existing_run_id = str(existing.id)
- transaction.on_commit(lambda: _start_review_workflow(existing_run_id, team_id), using=run_write_db)
- logger.info(
- "stamphog_inbox_pr_already_reviewed",
- repository=repository,
- pr_number=pr_number,
- existing_status=existing.status,
- )
- return
- _supersede_prior_runs(pr_obj)
- review_run = ReviewRun.objects.for_team(team_id).create(
- team_id=team_id,
- pull_request=pr_obj,
- head_sha=head_sha,
- delivery_id=None,
- status=ReviewRunStatus.QUEUED,
- # Always self-driving on this leg: it exists only for inbox-linked PRs.
- output={"inbox_review": inbox_review, "review_trigger": ReviewTrigger.SELF_DRIVING.value},
- )
- review_run_id = str(review_run.id)
- # A post-commit start failure propagates into the retry below; the retry re-enters
- # through the dedupe above and restarts the still-QUEUED run.
- transaction.on_commit(lambda: _start_review_workflow(review_run_id, team_id), using=run_write_db)
+ queued = _queue_review_at_head(
+ repo_config,
+ pr,
+ head_sha,
+ # Always self-driving on this leg: it exists only for inbox-linked PRs.
+ output={"inbox_review": inbox_review, "review_trigger": ReviewTrigger.SELF_DRIVING.value},
+ )
except Exception as e:
logger.exception("stamphog_inbox_pr_create_run_failed", repository=repository, pr_number=pr_number)
raise cast(Any, process_inbox_pr_review).retry(exc=e)
+ if queued.run is None:
+ logger.info("stamphog_inbox_pr_stale_snapshot", repository=repository, pr_number=pr_number)
+ return
+ if not queued.created:
+ logger.info(
+ "stamphog_inbox_pr_already_reviewed",
+ repository=repository,
+ pr_number=pr_number,
+ existing_status=queued.run.status,
+ )
+ return
logger.info(
"stamphog_inbox_pr_review_queued",
repository=repository,
pr_number=pr_number,
- review_run_id=review_run_id,
+ review_run_id=str(queued.run.id),
+ team_id=team_id,
+ )
+
+
+_MANUAL_SKIP_MESSAGES = {
+ "draft": "Stamphog does not review draft pull requests. Mark the pull request as ready for review, then request again.",
+ "bot_author": "Stamphog does not review pull requests opened by bots. This change needs a human reviewer.",
+ "untrusted_author_association": "Stamphog only reviews pull requests from members and collaborators of the repository.",
+}
+
+# Transport-level GitHub failures. StamphogGitHubError is caught next to each call instead, because a
+# 404 on the PR fetch is a refusal of its own rather than an outage.
+_GITHUB_ERRORS = (GitHubRateLimitError, requests.RequestException)
+
+
+def _github_unavailable(repo: str, pr_number: int) -> ReviewRequestRefusedError:
+ logger.warning("stamphog_manual_review_github_failed", repository=repo, pr_number=pr_number, exc_info=True)
+ return ReviewRequestRefusedError(
+ ReviewRequestRefusal.GITHUB_UNAVAILABLE,
+ "Stamphog could not reach GitHub to check this request. Try again in a minute.",
+ )
+
+
+@frozen
+class QueuedReview:
+ """The run a manual review request points at, and whether the request created it."""
+
+ run: ReviewRun
+ created: bool
+
+
+def request_manual_review(team_id: int, user_id: int | None, repository: str, pr_number: int) -> QueuedReview:
+ """Queue a review of one PR because a PostHog user asked for it, and return the run that covers it.
+
+ The request stands in for the trigger label, so it bypasses the repo's review mode and nothing
+ else. Every other webhook gate still applies: open state, the draft, bot-author and
+ author-association pre-filters, and the PR author's own write access. No refusal here touches
+ GitHub, and a queued run enters the workflow through its dismiss-first step like every other run.
+
+ Runs synchronously in the API request, so the caller learns right away why a request was
+ refused. Raises ``ReviewRequestRefusedError`` with a message written for the requester.
+ """
+ repo_config = _reviewable_repo_config(team_id, repository)
+ if repo_config is None:
+ raise ReviewRequestRefusedError(
+ ReviewRequestRefusal.NOT_FOUND,
+ f"Stamphog is not connected and enabled for {repository} in this project. "
+ "Connect the repository in Stamphog settings and turn on reviews first.",
+ )
+ repo = repo_config.repository
+ try:
+ pr = StamphogGitHubClient(repo_config.installation_id).get_pr(repo, pr_number)
+ except StamphogGitHubError as e:
+ if e.status_code == 404:
+ raise ReviewRequestRefusedError(
+ ReviewRequestRefusal.NOT_FOUND, f"Pull request #{pr_number} was not found in {repo}."
+ )
+ raise _github_unavailable(repo, pr_number) from e
+ except _GITHUB_ERRORS as e:
+ raise _github_unavailable(repo, pr_number) from e
+ if (pr.get("state") or "") != "open":
+ raise ReviewRequestRefusedError(
+ ReviewRequestRefusal.NOT_REVIEWABLE,
+ f"Pull request #{pr_number} is closed, so Stamphog will not review it.",
+ )
+ skip_reason = _review_skip_reason(pr)
+ if skip_reason is not None:
+ raise ReviewRequestRefusedError(ReviewRequestRefusal.NOT_REVIEWABLE, _MANUAL_SKIP_MESSAGES[skip_reason])
+ try:
+ author_below_write = _author_lacks_write_permission(repo_config, repo, pr)
+ except (StamphogGitHubError, *_GITHUB_ERRORS) as e:
+ raise _github_unavailable(repo, pr_number) from e
+ if author_below_write:
+ raise ReviewRequestRefusedError(
+ ReviewRequestRefusal.NOT_REVIEWABLE,
+ f"The author of pull request #{pr_number} does not have write access to {repo}, "
+ "so Stamphog will not review it.",
+ )
+
+ queued = _queue_review_at_head(
+ repo_config,
+ pr,
+ pr["head"]["sha"],
+ output={"manual_review": {"acting_user_id": user_id}, "review_trigger": ReviewTrigger.MANUAL.value},
+ )
+ if queued.run is None:
+ raise ReviewRequestRefusedError(
+ ReviewRequestRefusal.NOT_REVIEWABLE,
+ f"Pull request #{pr_number} changed while the request was checked. Request the review again.",
+ )
+ logger.info(
+ "stamphog_manual_review_requested",
+ repository=repo,
+ pr_number=pr_number,
+ review_run_id=str(queued.run.id),
+ created=queued.created,
team_id=team_id,
)
+ return QueuedReview(run=queued.run, created=queued.created)
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index 1ed9831ebfc4..2ca2d631ed1a 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -17,7 +17,6 @@ single verdict JSON.
from __future__ import annotations
import os
-import re
import json
import time
import shlex
@@ -63,6 +62,7 @@ from products.stamphog.backend.logic.reviewer import (
build_reviewer_invocation,
parse_reviewer_output,
)
+from products.stamphog.backend.logic.scrubbing import neutralize_active_markdown, scrub_credentials
from products.stamphog.backend.models import PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfig
from products.stamphog.backend.temporal.constants import (
CLONE_STEP_TIMEOUT_SECONDS,
@@ -307,7 +307,7 @@ def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConf
POSTHOG_API_KEY/POSTHOG_HOST let the engine emit its stamphog_review_completed event and LLM
traces from inside the sandbox. The capture key is a public project write token — the same class of
token every frontend snippet ships — so its blast radius is event spam, not data access; it's still
- added to _llm_env_secrets so persisted output stays tidy. STAMPHOG_EXTRA_PROPERTIES stamps the
+ added to llm_env_secrets so persisted output stays tidy. STAMPHOG_EXTRA_PROPERTIES stamps the
hosted runtime/team/run context onto those events.
"""
gateway = resolve_ai_gateway_config()
@@ -667,7 +667,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
sandbox_class = get_sandbox_class_for_backend(_resolve_sandbox_backend())
environment, gateway = _reviewer_environment(run)
# Per-run credential, not in the worker env — scrub it explicitly wherever sandbox output
- # is persisted or raised (_llm_env_secrets only covers worker-env values).
+ # is persisted or raised (llm_env_secrets only covers worker-env values).
gateway_token = environment["AI_GATEWAY_API_KEY"]
# Every path from here releases the token, including a failed claim read or save.
try:
@@ -735,7 +735,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
# both stored on run.output and re-read verbatim to render the verdict posted to GitHub.
run.output = {
**(run.output or {}),
- "reviewer_raw": _scrub_credentials(result.stdout, token, gateway_token),
+ "reviewer_raw": scrub_credentials(result.stdout, token, gateway_token),
"reviewer_exit_code": result.exit_code,
}
run.save(update_fields=["output", "updated_at"])
@@ -745,7 +745,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
# This message reaches run.error, so keep the stderr in the worker log only.
activity.logger.error(
f"Reviewer exited with code {result.exit_code} for run {run.id}: "
- f"{_scrub_credentials(result.stderr, token, gateway_token)[:500]}"
+ f"{scrub_credentials(result.stderr, token, gateway_token)[:500]}"
)
raise RuntimeError(f"reviewer exited with code {result.exit_code}")
except Exception as exc:
@@ -972,7 +972,7 @@ def post_verdict(input: StamphogReviewInput) -> dict:
run.gate_result = parsed.gate_result
# reviewer_raw was scrubbed on the way into the row; this re-scrub covers the worker's own LLM
# env secrets, the same belt-and-braces the review body gets below.
- run.change_summary = _scrub_credentials(parsed.change_summary)
+ run.change_summary = scrub_credentials(parsed.change_summary)
if parsed.stamphog_version:
run.output = {**output, "stamphog_version": parsed.stamphog_version}
@@ -1039,7 +1039,7 @@ def post_verdict(input: StamphogReviewInput) -> dict:
if adopted_review_id is not None:
run.posted_review_id = adopted_review_id
else:
- body = _scrub_credentials(_verdict_body(parsed, ReviewVerdict.APPROVED, relabel_label))
+ body = scrub_credentials(_verdict_body(parsed, ReviewVerdict.APPROVED, relabel_label))
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
@@ -1237,58 +1237,6 @@ def _harden_reviewer_command(command: Sequence[str] | str) -> str:
return shlex.join(parts)
-def _llm_env_secrets() -> list[str]:
- """Non-empty LLM credential values in the worker env, gathered for output scrubbing.
-
- These reach the sandbox via ``_reviewer_environment``; a confused or compromised
- reviewer could echo them into stdout or the verdict. Redacting them server-side,
- independent of model behavior, is what keeps a leaked key out of the PR and the DB.
- POSTHOG_API_KEY is a public write token (spam-only blast radius) — scrubbed for tidiness.
- """
- return [
- value
- for key in ("AI_GATEWAY_API_KEY", "ANTHROPIC_API_KEY", "AI_GATEWAY_URL", "POSTHOG_API_KEY")
- if (value := os.environ.get(key))
- ]
-
-
-# Inline markdown images and raw <img> tags in text GitHub renders — both are removed outright,
-# URL included. Reference-style image forms are handled by the ``![`` demotion below.
-_MARKDOWN_IMAGE_RE = re.compile(r"!\[[^\]]*\]\([^)]*\)|<img\b[^>]*>", re.IGNORECASE)
-
-
-def _neutralize_active_markdown(text: str) -> str:
- """Remove auto-fetched markdown constructs from reviewer-authored text before it reaches GitHub.
-
- The reviewer LLM reads untrusted PR content, so its output can be prompt-injected. Credential
- scrubbing is exact-string only — a token re-encoded (base64, split) into an image URL slips
- through, and GitHub fetching the image on render (through its camo proxy, no click needed) would
- exfiltrate it OUTSIDE the sandbox egress allowlist.
-
- Inline images and <img> tags are removed URL-and-all. Every OTHER markdown image form —
- reference ``![a][ref]``, collapsed, shortcut — starts with ``![``, so the trailing demotion to
- ``[`` turns anything left into a plain link, which GitHub never fetches without a click.
- Deliberately a syntax demotion rather than an enumeration of forms: an image form this function's
- author didn't think of still gets demoted. Plain links stay clickable, so legitimate references
- to code and PRs survive.
- """
- return _MARKDOWN_IMAGE_RE.sub("[image removed]", text).replace("![", "[")
-
-
-def _scrub_credentials(text: str, *secrets: str) -> str:
- """Redact credential material before it reaches ``ReviewRun``, the logs, or GitHub.
-
- Scrubs the passed GitHub token / basic-auth material plus any LLM credentials present
- in the worker env — deterministic, so it does not depend on what the reviewer emits.
- """
- for secret in secrets:
- if secret:
- text = text.replace(secret, "***")
- for secret in _llm_env_secrets():
- text = text.replace(secret, "[redacted]")
- return text
-
-
@frozen
class _GitCredential:
"""The installation token in the two shapes a sandbox git command needs.
@@ -1299,7 +1247,7 @@ class _GitCredential:
# The ``git`` prefix to run GitHub-facing commands with.
command: str
- # The raw credential, for _scrub_credentials to strip from anything the command echoes back.
+ # The raw credential, for scrub_credentials to strip from anything the command echoes back.
secret: str = field(repr=False)
@@ -1358,9 +1306,9 @@ def _clone_pr(
try:
result = sandbox.execute(command, timeout_seconds=_step_timeout(deadline, CLONE_STEP_TIMEOUT_SECONDS))
except Exception as exc:
- raise RuntimeError(_scrub_credentials(str(exc), token, credential.secret)) from None
+ raise RuntimeError(scrub_credentials(str(exc), token, credential.secret)) from None
if result.exit_code != 0:
- raise RuntimeError(f"{failure_prefix}: {_scrub_credentials(result.stderr, token, credential.secret)[:500]}")
+ raise RuntimeError(f"{failure_prefix}: {scrub_credentials(result.stderr, token, credential.secret)[:500]}")
clone = (
f"rm -rf {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && "
@@ -1506,7 +1454,7 @@ def _prefetch_review_blobs(
# failure can echo the argv back.
activity.logger.warning(
f"stamphog: review blob prefetch exited {result.exit_code}; "
- f"git will fetch as it reads: {_scrub_credentials(result.stderr, token, credential.secret)[:300]}"
+ f"git will fetch as it reads: {scrub_credentials(result.stderr, token, credential.secret)[:300]}"
)
@@ -1718,7 +1666,7 @@ def _post_non_approval_review(
"""
if (run.output or {}).get(NON_APPROVAL_REVIEW_ID_KEY) is not None:
return
- review = client.post_comment_review(repo, pull_request.pr_number, _scrub_credentials(body), run.head_sha)
+ review = client.post_comment_review(repo, pull_request.pr_number, scrub_credentials(body), run.head_sha)
run.output = {**(run.output or {}), NON_APPROVAL_REVIEW_ID_KEY: _comment_id(review)}
ReviewRun.objects.for_team(team_id).filter(id=run.id).update(output=run.output, updated_at=timezone.now())
@@ -1795,7 +1743,7 @@ def _verdict_body(parsed: ReviewerVerdict, verdict: str, relabel_label: str | No
if relabel_label:
headline += f"\n\nRe-add the `{relabel_label}` label to request another review once you have addressed this."
detail = parsed.review_body or _reasoning_detail(parsed)
- return f"{headline}\n\n{_neutralize_active_markdown(detail)}".rstrip()
+ return f"{headline}\n\n{neutralize_active_markdown(detail)}".rstrip()
def _reasoning_detail(parsed: ReviewerVerdict) -> str:
diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.py
index 76eecb5a61a9..a5f6ed45af67 100644
--- a/products/stamphog/backend/tests/test_api.py
+++ b/products/stamphog/backend/tests/test_api.py
@@ -1,3 +1,4 @@
+import json
from typing import Any
import pytest
@@ -25,6 +26,7 @@ from products.stamphog.backend.facade.enums import ChannelResolutionSource, Dige
from products.stamphog.backend.models import DigestRun, PullRequest, ReviewRun, StamphogRepoConfig
from products.stamphog.backend.presentation.serializers import StamphogRepoConfigWriteSerializer
from products.stamphog.backend.presentation.views import _INSTALL_STATE_SALT
+from products.stamphog.backend.tests import fakes
from products.stamphog.backend.tests.conftest import PRODUCT_DATABASES, StamphogTeamScopedTestMixin
_VIEWS = "products.stamphog.backend.presentation.views"
@@ -560,6 +562,7 @@ class TestReviewRunAPI(StamphogTeamScopedTestMixin, APIBaseTest):
# whether or not the repo also reviews every PR event.
("self_driving_beats_all_mode", ReviewMode.ALL, {"inbox_review": {"trigger": "inbox"}}, "self_driving"),
("self_driving_beats_label_mode", ReviewMode.LABEL, {"inbox_review": {"trigger": "inbox"}}, "self_driving"),
+ ("manual_beats_label_mode", ReviewMode.LABEL, {"manual_review": {"acting_user_id": 1}}, "manual"),
("label_mode", ReviewMode.LABEL, {}, "label"),
("all_mode", ReviewMode.ALL, {}, "all"),
]
@@ -590,16 +593,6 @@ class TestReviewRunAPI(StamphogTeamScopedTestMixin, APIBaseTest):
assert response.status_code == status.HTTP_200_OK, response.content
assert response.json()["results"] == []
- def test_readonly_viewset_rejects_writes(self) -> None:
- # ReviewRun is created by the webhook/task pipeline, never directly
- # by API clients; the viewset must stay read-only.
- response = self.client.post(
- self.url,
- {"repository": "PostHog/posthog", "pr_number": 1, "pr_url": "x", "head_sha": "abc"},
- format="json",
- )
- assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
-
def test_output_excludes_raw_repo_content(self) -> None:
# run.output holds the full PR payload, changed-file patches, default-branch policy files, and
# raw reviewer stdout. A project member without repo access can read this endpoint, so the API
@@ -623,6 +616,183 @@ class TestReviewRunAPI(StamphogTeamScopedTestMixin, APIBaseTest):
assert leaked not in output
+class TestReviewRequestAPI(StamphogTeamScopedTestMixin, APIBaseTest):
+ databases = PRODUCT_DATABASES
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.url = f"/api/projects/{self.team.id}/stamphog/review_runs/"
+ self.repo_config = StamphogRepoConfig.objects.unscoped().create(
+ team_id=self.team.id,
+ repository="PostHog/posthog",
+ installation_id="77",
+ enabled=True,
+ connected_by_user_id=self.user.id,
+ # Label mode with no label on the PR: the request is what stands in for the label.
+ review_mode=ReviewMode.LABEL,
+ )
+ self.github = fakes.GitHubRecorder()
+ self.github.register_pr("PostHog/posthog", 5, self._pr())
+ for target, replacement in (
+ ("products.stamphog.backend.logic.github_client.github_request", self.github.github_request),
+ (
+ "products.stamphog.backend.logic.github_client.remember_observed_core_limit",
+ fakes.noop_remember_observed_core_limit,
+ ),
+ (
+ "products.stamphog.backend.logic.github_client.raise_if_github_rate_limited",
+ fakes.noop_raise_if_github_rate_limited,
+ ),
+ (f"{_CLIENT}._get_installation_token", lambda *_args, **_kwargs: "ghs_test"),
+ ("products.stamphog.backend.tasks.tasks.transaction.on_commit", lambda fn, using=None: fn()),
+ ):
+ patcher = patch(target, replacement)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ workflow_patcher = patch("products.stamphog.backend.tasks.tasks.execute_stamphog_review_workflow")
+ self.start_workflow = workflow_patcher.start()
+ self.addCleanup(workflow_patcher.stop)
+
+ def _pr(self, **overrides: Any) -> dict[str, Any]:
+ pr = fakes.build_pull_request_event(
+ action="opened",
+ installation_id="77",
+ repo="PostHog/posthog",
+ number=5,
+ title="feat: a change",
+ body="",
+ author_login="bob",
+ head_sha="head1",
+ head_ref="feat/change",
+ base_sha="base1",
+ )["pull_request"]
+ return {**pr, **overrides}
+
+ def _request(self) -> Any:
+ return self.client.post(self.url, {"repository": "posthog/posthog", "pr_number": 5}, format="json")
+
+ def test_request_queues_a_manual_run_past_label_mode(self) -> None:
+ response = self._request()
+
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ body = response.json()
+ assert body["created"] is True
+ assert body["run"]["status"] == "queued"
+ assert body["run"]["trigger"] == "manual"
+ run = ReviewRun.objects.unscoped().get(id=body["run"]["id"])
+ assert run.head_sha == "head1"
+ assert run.output == {"manual_review": {"acting_user_id": self.user.id}, "review_trigger": "manual"}
+ self.start_workflow.assert_called_once_with(review_run_id=str(run.id), team_id=self.team.id)
+
+ @parameterized.expand(
+ [
+ # A QUEUED run lost its workflow start, so a repeat request restarts it.
+ ("queued_restarts", ReviewRunStatus.QUEUED, None, False, True),
+ ("reviewing_is_returned", ReviewRunStatus.REVIEWING, None, False, False),
+ ("completed_is_returned", ReviewRunStatus.COMPLETED, None, False, False),
+ ("failed_is_replaced", ReviewRunStatus.FAILED, "master", True, True),
+ ("same_base_is_returned", ReviewRunStatus.COMPLETED, "master", False, False),
+ # A base retarget changes the diff without moving the head.
+ ("other_base_is_replaced", ReviewRunStatus.COMPLETED, "feat/parent", True, True),
+ ]
+ )
+ def test_repeat_request_dedupes_on_the_current_head(
+ self,
+ _name: str,
+ existing_status: ReviewRunStatus,
+ reviewed_base_ref: str | None,
+ expect_created: bool,
+ expect_start: bool,
+ ) -> None:
+ first = self._request().json()["run"]["id"]
+ output = {"pr": {"base": {"ref": reviewed_base_ref}}} if reviewed_base_ref else {}
+ ReviewRun.objects.unscoped().filter(id=first).update(status=existing_status, output=output)
+ self.start_workflow.reset_mock()
+
+ response = self._request()
+
+ assert response.status_code == (201 if expect_created else 200), response.content
+ body = response.json()
+ assert body["created"] is expect_created
+ assert (body["run"]["id"] == first) is not expect_created
+ assert self.start_workflow.called is expect_start
+
+ @parameterized.expand(
+ [
+ ("draft", {"draft": True}, "read"),
+ ("bot_author", {"user": {"login": "renovate[bot]", "type": "Bot"}}, "write"),
+ ("fork_author", {"author_association": "NONE"}, "write"),
+ ("closed", {"state": "closed"}, "write"),
+ ("author_below_write", {}, "read"),
+ ]
+ )
+ def test_refused_requests_create_no_run(self, _name: str, pr_overrides: dict, author_permission: str) -> None:
+ self.github.register_pr("PostHog/posthog", 5, self._pr(**pr_overrides))
+ self.github.collaborator_permissions[("PostHog/posthog", "bob")] = author_permission
+
+ response = self._request()
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.content
+ assert response.json()["code"] == "not_reviewable"
+ assert not ReviewRun.objects.unscoped().filter(team_id=self.team.id).exists()
+ assert self.github.github_writes == []
+
+ def test_request_needs_the_write_scope(self) -> None:
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="read-only", user=self.user, secure_value=hash_key_value(key_value), scopes=["stamphog:read"]
+ )
+ self.client.logout()
+
+ response = self.client.post(
+ self.url,
+ {"repository": "PostHog/posthog", "pr_number": 5},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert not ReviewRun.objects.unscoped().filter(team_id=self.team.id).exists()
+
+ @parameterized.expand([("reviewed", "ok"), ("not_reviewed_yet", None), ("malformed_output", "malformed")])
+ def test_retrieve_returns_the_reviewer_reasoning(self, _name: str, stored: str | None) -> None:
+ pull_request = PullRequest.objects.unscoped().create(
+ team_id=self.team.id, repo_config=self.repo_config, pr_number=5, pr_url="https://github.com/x/y/pull/5"
+ )
+ engine_output: dict[str, Any] = {
+ "final_verdict": "REFUSED",
+ "reviewer": {
+ "reasoning": "Touches auth. ![x](https://evil.example.com/leak.png)",
+ "issues": ["Missing test"],
+ "change_summary": "Adds a login check.",
+ },
+ "review_body": "Refused: touches auth.",
+ "gates": [],
+ }
+ if stored == "malformed":
+ engine_output = {"final_verdict": "ERROR", "reviewer": "bad", "gates": 1}
+ output = {"reviewer_raw": f"uv noise\n{json.dumps(engine_output)}"} if stored else {}
+ run = ReviewRun.objects.unscoped().create(
+ team_id=self.team.id, pull_request=pull_request, head_sha="head1", output=output
+ )
+
+ body = self.client.get(f"{self.url}{run.id}/").json()
+
+ reasoning = body["reasoning"]
+ if stored == "ok":
+ # The image is removed before the text leaves the API, because an MCP client can render it.
+ assert reasoning == {
+ "reasoning": "Touches auth. [image removed]",
+ "showstoppers": ["Missing test"],
+ "review_body": "Refused: touches auth.",
+ "change_summary": "Adds a login check.",
+ }
+ else:
+ assert reasoning == dict.fromkeys(["reasoning", "showstoppers", "review_body", "change_summary"])
+ assert "reviewer_raw" not in body["output"]
+ assert self.client.get(self.url).json()["results"][0]["reasoning"] is None
+
+
class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
databases = PRODUCT_DATABASES
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 56edc8fee251..94aecf03d08c 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -731,7 +731,7 @@ def test_a_go_gateway_url_without_a_key_fails_closed(team, user, stamphog_chain:
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_scoped_token_is_scrubbed_from_persisted_reviewer_output(team, stamphog_chain: StamphogChain) -> None:
- # The per-run phe_ is not in the worker env, so _llm_env_secrets cannot catch it; the explicit
+ # The per-run phe_ is not in the worker env, so llm_env_secrets cannot catch it; the explicit
# gateway_token scrub must keep it out of ReviewRun.output.
_repo_config(team.id)
event = _register_review(stamphog_chain, 117, "sha117a")
diff --git a/products/stamphog/frontend/generated/api.schemas.ts b/products/stamphog/frontend/generated/api.schemas.ts
index 606a88867ea7..42d9313b9264 100644
--- a/products/stamphog/frontend/generated/api.schemas.ts
+++ b/products/stamphog/frontend/generated/api.schemas.ts
@@ -288,6 +288,7 @@ export interface StamphogSyncInstallationResponseApi {
/**
* * `self_driving` - SELF_DRIVING
+ * * `manual` - MANUAL
* * `label` - LABEL
* * `all` - ALL
*/
@@ -295,6 +296,7 @@ export type ReviewRunTriggerEnumApi = (typeof ReviewRunTriggerEnumApi)[keyof typ
export const ReviewRunTriggerEnumApi = {
SelfDriving: 'self_driving',
+ Manual: 'manual',
Label: 'label',
All: 'all',
} as const
@@ -356,8 +358,8 @@ export interface _GateResultSummaryApi {
* Allowlisted, non-sensitive slice of ``ReviewRun.output``.
*
* The raw ``output`` blob also holds the reviewer's stdout, the full PR payload, changed-file patches,
- * and default-branch policy file contents — repository content a project member without repo access
- * must never read. Only these derived, content-free fields are exposed.
+ * and default-branch policy file contents, none of which the API returns. The reviewer's reasoning,
+ * the text stamphog posts on GitHub, is parsed out of the stdout and returned as ``reasoning``.
*/
export interface _ReviewOutputSummaryApi {
/** Version of the stamphog engine that produced this review, if it reported one. */
@@ -366,6 +368,32 @@ export interface _ReviewOutputSummaryApi {
readonly reviewer_exit_code: number
}
+/**
+ * The reviewer's reasoning for one run, the same text stamphog posts as its GitHub review.
+ */
+export interface _ReviewReasoningApi {
+ /**
+ * The reviewer's explanation of its verdict.
+ * @nullable
+ */
+ readonly reasoning: string | null
+ /**
+ * Issues the reviewer found that block approval.
+ * @nullable
+ */
+ readonly showstoppers: readonly string[] | null
+ /**
+ * The review text stamphog posts on GitHub: the reasoning, the judgment points, and the gate outcome.
+ * @nullable
+ */
+ readonly review_body: string | null
+ /**
+ * A plain-language summary of what the change does.
+ * @nullable
+ */
+ readonly change_summary: string | null
+}
+
export interface ReviewRunApi {
readonly id: string
/** ID of the pull request this review run belongs to. */
@@ -389,9 +417,10 @@ export interface ReviewRunApi {
* @nullable
*/
readonly delivery_id: string | null
- /** What caused this run to exist: self-driving inbox provenance, the repo's trigger label, or the repo reviewing every PR event.
+ /** What caused this run to exist: self-driving inbox provenance, a manual request through the API, the repo's trigger label, or the repo reviewing every PR event.
*
* * `self_driving` - SELF_DRIVING
+ * * `manual` - MANUAL
* * `label` - LABEL
* * `all` - ALL */
readonly trigger: ReviewRunTriggerEnumApi
@@ -415,8 +444,10 @@ export interface ReviewRunApi {
readonly verdict: ReviewRunVerdictEnumApi
/** Allowlisted deterministic gate outcome (gate_blocked, final_verdict). The nested gate, classification, and policy sub-objects are excluded — they carry changed-file paths and policy scopes, repository content a project member without repo access must not read. */
readonly gate_result: _GateResultSummaryApi
- /** Allowlisted, non-sensitive subset of the reviewer output blob (stamphog version, reviewer exit code). The raw reviewer stdout, PR payload, changed-file patches, and policy file contents are deliberately excluded — they carry repository content a project member without repo access must not read. */
+ /** Allowlisted subset of the reviewer output blob (stamphog version, reviewer exit code). The raw reviewer stdout, PR payload, changed-file patches, and policy file contents are excluded. The reviewer's reasoning, the text stamphog posts on GitHub, is in `reasoning` instead. */
readonly output: _ReviewOutputSummaryApi
+ /** The reviewer's reasoning, the same text stamphog posts as its GitHub review. Returned only when retrieving a single run, and null in list results. Its fields are null until the reviewer has run. */
+ readonly reasoning: _ReviewReasoningApi | null
/** Error message if the run failed, blank otherwise. */
readonly error: string
/**
@@ -454,6 +485,29 @@ export interface PaginatedReviewRunListApi {
results: ReviewRunApi[]
}
+/**
+ * Request body for asking stamphog to review one pull request.
+ */
+export interface ReviewRequestApi {
+ /** Full name of the GitHub repository, e.g. 'PostHog/posthog'. It must be connected and enabled in Stamphog. */
+ repository: string
+ /**
+ * Pull request number on GitHub.
+ * @minimum 1
+ */
+ pr_number: number
+}
+
+/**
+ * The review run a request points at.
+ */
+export interface ReviewRequestResponseApi {
+ /** The review run for the pull request's current head. Poll it by id until status is terminal (completed, gated, failed, or superseded). */
+ readonly run: ReviewRunApi
+ /** True when this request queued a new run. False when a queued, running, or finished run already covered the current head, which is returned instead. */
+ readonly created: boolean
+}
+
export type StamphogDigestRunsListParams = {
/**
* Number of results to return per page.
@@ -521,7 +575,7 @@ export type StamphogReviewRunsListParams = {
*/
status?: string
/**
- * Filter by what caused the run: self_driving, label, or all.
+ * Filter by what caused the run: self_driving, manual, label, or all.
*/
trigger?: StamphogReviewRunsListTrigger
}
@@ -532,5 +586,6 @@ export type StamphogReviewRunsListTrigger =
export const StamphogReviewRunsListTrigger = {
All: 'all',
Label: 'label',
+ Manual: 'manual',
SelfDriving: 'self_driving',
} as const
diff --git a/products/stamphog/frontend/generated/api.ts b/products/stamphog/frontend/generated/api.ts
index 9d44df64289a..6b703f6694b0 100644
--- a/products/stamphog/frontend/generated/api.ts
+++ b/products/stamphog/frontend/generated/api.ts
@@ -15,6 +15,8 @@ import type {
PaginatedStamphogPullRequestListApi,
PaginatedStamphogRepoConfigListApi,
PatchedStamphogRepoConfigWriteApi,
+ ReviewRequestApi,
+ ReviewRequestResponseApi,
ReviewRunApi,
StamphogDigestRunsListParams,
StamphogInstallInfoApi,
@@ -306,7 +308,7 @@ export const getStamphogReviewRunsListUrl = (projectId: string, params?: Stampho
}
/**
- * Read-only history of stamphog review runs, filterable by repository, PR number, and status.
+ * History of stamphog review runs, filterable by repository, PR number, and status, plus manual review requests.
*/
export const stamphogReviewRunsList = async (
projectId: string,
@@ -319,12 +321,32 @@ export const stamphogReviewRunsList = async (
})
}
+export const getStamphogReviewRunsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/stamphog/review_runs/`
+}
+
+/**
+ * History of stamphog review runs, filterable by repository, PR number, and status, plus manual review requests.
+ */
+export const stamphogReviewRunsCreate = async (
+ projectId: string,
+ reviewRequestApi: ReviewRequestApi,
+ options?: RequestInit
+): Promise<ReviewRequestResponseApi> => {
+ return apiMutator<ReviewRequestResponseApi>(getStamphogReviewRunsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(reviewRequestApi),
+ })
+}
+
export const getStamphogReviewRunsRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/stamphog/review_runs/${id}/`
}
/**
- * Read-only history of stamphog review runs, filterable by repository, PR number, and status.
+ * History of stamphog review runs, filterable by repository, PR number, and status, plus manual review requests.
*/
export const stamphogReviewRunsRetrieve = async (
projectId: string,
diff --git a/products/stamphog/frontend/generated/api.zod.ts b/products/stamphog/frontend/generated/api.zod.ts
index 3645ea52a5c2..cb0aebc98d17 100644
--- a/products/stamphog/frontend/generated/api.zod.ts
+++ b/products/stamphog/frontend/generated/api.zod.ts
@@ -120,3 +120,18 @@ export const StamphogRepoConfigsSyncInstallationCreateBody = /* @__PURE__ */ zod
.describe(
"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."
)
+
+/**
+ * History of stamphog review runs, filterable by repository, PR number, and status, plus manual review requests.
+ */
+
+export const StamphogReviewRunsCreateBody = /* @__PURE__ */ zod
+ .object({
+ repository: zod
+ .string()
+ .describe(
+ "Full name of the GitHub repository, e.g. 'PostHog\/posthog'. It must be connected and enabled in Stamphog."
+ ),
+ pr_number: zod.number().min(1).describe('Pull request number on GitHub.'),
+ })
+ .describe('Request body for asking stamphog to review one pull request.')
diff --git a/products/stamphog/frontend/scenes/StamphogRunsScene/runDisplay.ts b/products/stamphog/frontend/scenes/StamphogRunsScene/runDisplay.ts
index dcb3a850c095..f70281ebceab 100644
--- a/products/stamphog/frontend/scenes/StamphogRunsScene/runDisplay.ts
+++ b/products/stamphog/frontend/scenes/StamphogRunsScene/runDisplay.ts
@@ -33,6 +33,7 @@ const STATUS_DISPLAY: Record<ReviewRunStatusEnumApi, OutcomeDisplay> = {
const TRIGGER_LABEL: Record<ReviewRunTriggerEnumApi, string> = {
[ReviewRunTriggerEnumApi.SelfDriving]: 'Self-driving',
+ [ReviewRunTriggerEnumApi.Manual]: 'Requested',
[ReviewRunTriggerEnumApi.Label]: 'Label',
[ReviewRunTriggerEnumApi.All]: 'Every PR',
}
diff --git a/products/stamphog/mcp/tools.yaml b/products/stamphog/mcp/tools.yaml
index 760d880b4e5d..934e8ec7f906 100644
--- a/products/stamphog/mcp/tools.yaml
+++ b/products/stamphog/mcp/tools.yaml
@@ -123,6 +123,26 @@ tools:
stamphog-repo-configs-update:
operation: stamphog_repo_configs_update
enabled: false
+ stamphog-review-runs-create:
+ operation: stamphog_review_runs_create
+ enabled: true
+ scopes:
+ - stamphog:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Request a stamphog review
+ description: >
+ Ask stamphog to review one pull request now, by `repository` (owner/name) and `pr_number`. The repository
+ must be connected and enabled in Stamphog. The request replaces the trigger label, so it works in label mode
+ too, but every other rule still applies: stamphog refuses drafts, closed PRs, bot-authored PRs, PRs from
+ outside the repository, and PRs whose author lacks write access, and the error message says why. Stamphog
+ decides the verdict itself: a passing review posts a real GitHub approval, anything else posts a comment.
+ The review runs in the background, so this returns the run right away (status `queued`). Poll
+ `stamphog-review-runs-get` with its id for the verdict and reasoning. When a run already covers the PR's
+ current head, that run is returned with `created: false` instead of starting another.
+ feature_flag: stamphog
stamphog-review-runs-get:
operation: stamphog_review_runs_retrieve
enabled: true
@@ -135,9 +155,11 @@ tools:
title: Get stamphog review run
description: >
Get a single review run by id — the record of one automated review pass over a pull request. Returns the
- lifecycle `status`, final `verdict`, and an allowlisted `gate_result` (gate_blocked, final_verdict). The raw
- reviewer transcript, PR payload, and policy contents are deliberately not exposed — they carry repository
- content a project member without repo access must not read.
+ lifecycle `status`, final `verdict`, an allowlisted `gate_result` (gate_blocked, final_verdict), and the
+ reviewer's `reasoning` (its explanation, the showstoppers that blocked approval, the review text stamphog
+ posts on GitHub, and a plain-language change summary). The reasoning fields are null until the reviewer has
+ run. Poll this after `stamphog-review-runs-create` until `status` is completed, gated, failed, or
+ superseded. The raw reviewer transcript, PR payload, patches, and policy contents are not exposed.
feature_flag: stamphog
stamphog-review-runs-list:
operation: stamphog_review_runs_list
@@ -154,9 +176,10 @@ tools:
List stamphog's automated review runs for pull requests in this project, newest first. Filter by
`repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Each run reports its
lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the
- reviewer ran. The raw reviewer output (full reasoning transcript) is omitted from list results — use
- `stamphog-review-runs-get` for the full detail.
+ reviewer ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to
+ read it.
feature_flag: stamphog
response:
exclude:
- output
+ - reasoning
diff --git a/products/stamphog/packages/pr-approval-agent/reviewer.py b/products/stamphog/packages/pr-approval-agent/reviewer.py
index 4d1b403e2672..bd7397364fed 100644
--- a/products/stamphog/packages/pr-approval-agent/reviewer.py
+++ b/products/stamphog/packages/pr-approval-agent/reviewer.py
@@ -182,7 +182,7 @@ def _validate_verdict(result: dict) -> dict:
# ANTHROPIC_API_KEY), and Read/Grep/Glob are NOT path-restricted, so the agent can
# in principle read those env values. What actually prevents key exfiltration to the
# PR / DB is the deterministic server-side output scrub in stamphog's activities.py
- # (_scrub_credentials in run_review_in_sandbox and post_verdict), not this hook.
+ # (scrub_credentials in run_review_in_sandbox and post_verdict), not this hook.
# TODO: re-enable once the SDK hook bug is fixed.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a8cc09c8b2d6..9559b1726353 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11160,8 +11160,23 @@
},
"feature_flag": "stamphog"
},
+ "stamphog-review-runs-create": {
+ "description": "Ask stamphog to review one pull request now, by `repository` (owner/name) and `pr_number`. The repository must be connected and enabled in Stamphog. The request replaces the trigger label, so it works in label mode too, but every other rule still applies: stamphog refuses drafts, closed PRs, bot-authored PRs, PRs from outside the repository, and PRs whose author lacks write access, and the error message says why. Stamphog decides the verdict itself: a passing review posts a real GitHub approval, anything else posts a comment. The review runs in the background, so this returns the run right away (status `queued`). Poll `stamphog-review-runs-get` with its id for the verdict and reasoning. When a run already covers the PR's current head, that run is returned with `created: false` instead of starting another.",
+ "category": "Stamphog",
+ "feature": "stamphog",
+ "summary": "Request a stamphog review",
+ "title": "Request a stamphog review",
+ "required_scopes": ["stamphog:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "stamphog"
+ },
"stamphog-review-runs-get": {
- "description": "Get a single review run by id — the record of one automated review pass over a pull request. Returns the lifecycle `status`, final `verdict`, and an allowlisted `gate_result` (gate_blocked, final_verdict). The raw reviewer transcript, PR payload, and policy contents are deliberately not exposed — they carry repository content a project member without repo access must not read.",
+ "description": "Get a single review run by id — the record of one automated review pass over a pull request. Returns the lifecycle `status`, final `verdict`, an allowlisted `gate_result` (gate_blocked, final_verdict), and the reviewer's `reasoning` (its explanation, the showstoppers that blocked approval, the review text stamphog posts on GitHub, and a plain-language change summary). The reasoning fields are null until the reviewer has run. Poll this after `stamphog-review-runs-create` until `status` is completed, gated, failed, or superseded. The raw reviewer transcript, PR payload, patches, and policy contents are not exposed.",
"category": "Stamphog",
"feature": "stamphog",
"summary": "Get stamphog review run",
@@ -11176,7 +11191,7 @@
"feature_flag": "stamphog"
},
"stamphog-review-runs-list": {
- "description": "List stamphog's automated review runs for pull requests in this project, newest first. Filter by `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Each run reports its lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer ran. The raw reviewer output (full reasoning transcript) is omitted from list results — use `stamphog-review-runs-get` for the full detail.",
+ "description": "List stamphog's automated review runs for pull requests in this project, newest first. Filter by `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Each run reports its lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to read it.",
"category": "Stamphog",
"feature": "stamphog",
"summary": "List stamphog review runs",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index dfe8235711ee..5e62cd73f384 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11732,8 +11732,23 @@
},
"feature_flag": "stamphog"
},
+ "stamphog-review-runs-create": {
+ "description": "Ask stamphog to review one pull request now, by `repository` (owner/name) and `pr_number`. The repository must be connected and enabled in Stamphog. The request replaces the trigger label, so it works in label mode too, but every other rule still applies: stamphog refuses drafts, closed PRs, bot-authored PRs, PRs from outside the repository, and PRs whose author lacks write access, and the error message says why. Stamphog decides the verdict itself: a passing review posts a real GitHub approval, anything else posts a comment. The review runs in the background, so this returns the run right away (status `queued`). Poll `stamphog-review-runs-get` with its id for the verdict and reasoning. When a run already covers the PR's current head, that run is returned with `created: false` instead of starting another.",
+ "category": "Stamphog",
+ "feature": "stamphog",
+ "summary": "Request a stamphog review",
+ "title": "Request a stamphog review",
+ "required_scopes": ["stamphog:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "stamphog"
+ },
"stamphog-review-runs-get": {
- "description": "Get a single review run by id — the record of one automated review pass over a pull request. Returns the lifecycle `status`, final `verdict`, and an allowlisted `gate_result` (gate_blocked, final_verdict). The raw reviewer transcript, PR payload, and policy contents are deliberately not exposed — they carry repository content a project member without repo access must not read.",
+ "description": "Get a single review run by id — the record of one automated review pass over a pull request. Returns the lifecycle `status`, final `verdict`, an allowlisted `gate_result` (gate_blocked, final_verdict), and the reviewer's `reasoning` (its explanation, the showstoppers that blocked approval, the review text stamphog posts on GitHub, and a plain-language change summary). The reasoning fields are null until the reviewer has run. Poll this after `stamphog-review-runs-create` until `status` is completed, gated, failed, or superseded. The raw reviewer transcript, PR payload, patches, and policy contents are not exposed.",
"category": "Stamphog",
"feature": "stamphog",
"summary": "Get stamphog review run",
@@ -11748,7 +11763,7 @@
"feature_flag": "stamphog"
},
"stamphog-review-runs-list": {
- "description": "List stamphog's automated review runs for pull requests in this project, newest first. Filter by `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Each run reports its lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer ran. The raw reviewer output (full reasoning transcript) is omitted from list results — use `stamphog-review-runs-get` for the full detail.",
+ "description": "List stamphog's automated review runs for pull requests in this project, newest first. Filter by `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Each run reports its lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to read it.",
"category": "Stamphog",
"feature": "stamphog",
"summary": "List stamphog review runs",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index df95d0688c57..f42ed837ef52 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -63541,6 +63541,7 @@ export namespace Schemas {
/**
* * `self_driving` - SELF_DRIVING
+ * * `manual` - MANUAL
* * `label` - LABEL
* * `all` - ALL
*/
@@ -63549,6 +63550,7 @@ export namespace Schemas {
export const ReviewRunTriggerEnum = {
SelfDriving: 'self_driving',
+ Manual: 'manual',
Label: 'label',
All: 'all',
} as const;
@@ -63612,8 +63614,8 @@ export namespace Schemas {
* Allowlisted, non-sensitive slice of ``ReviewRun.output``.
*
* The raw ``output`` blob also holds the reviewer's stdout, the full PR payload, changed-file patches,
- * and default-branch policy file contents — repository content a project member without repo access
- * must never read. Only these derived, content-free fields are exposed.
+ * and default-branch policy file contents, none of which the API returns. The reviewer's reasoning,
+ * the text stamphog posts on GitHub, is parsed out of the stdout and returned as ``reasoning``.
*/
export interface _ReviewOutputSummary {
/** Version of the stamphog engine that produced this review, if it reported one. */
@@ -63622,6 +63624,32 @@ export namespace Schemas {
readonly reviewer_exit_code: number;
}
+ /**
+ * The reviewer's reasoning for one run, the same text stamphog posts as its GitHub review.
+ */
+ export interface _ReviewReasoning {
+ /**
+ * The reviewer's explanation of its verdict.
+ * @nullable
+ */
+ readonly reasoning: string | null;
+ /**
+ * Issues the reviewer found that block approval.
+ * @nullable
+ */
+ readonly showstoppers: readonly string[] | null;
+ /**
+ * The review text stamphog posts on GitHub: the reasoning, the judgment points, and the gate outcome.
+ * @nullable
+ */
+ readonly review_body: string | null;
+ /**
+ * A plain-language summary of what the change does.
+ * @nullable
+ */
+ readonly change_summary: string | null;
+ }
+
export interface ReviewRun {
readonly id: string;
/** ID of the pull request this review run belongs to. */
@@ -63645,9 +63673,10 @@ export namespace Schemas {
* @nullable
*/
readonly delivery_id: string | null;
- /** What caused this run to exist: self-driving inbox provenance, the repo's trigger label, or the repo reviewing every PR event.
+ /** What caused this run to exist: self-driving inbox provenance, a manual request through the API, the repo's trigger label, or the repo reviewing every PR event.
*
* * `self_driving` - SELF_DRIVING
+ * * `manual` - MANUAL
* * `label` - LABEL
* * `all` - ALL */
readonly trigger: ReviewRunTriggerEnum;
@@ -63671,8 +63700,10 @@ export namespace Schemas {
readonly verdict: ReviewRunVerdictEnum;
/** Allowlisted deterministic gate outcome (gate_blocked, final_verdict). The nested gate, classification, and policy sub-objects are excluded — they carry changed-file paths and policy scopes, repository content a project member without repo access must not read. */
readonly gate_result: _GateResultSummary;
- /** Allowlisted, non-sensitive subset of the reviewer output blob (stamphog version, reviewer exit code). The raw reviewer stdout, PR payload, changed-file patches, and policy file contents are deliberately excluded — they carry repository content a project member without repo access must not read. */
+ /** Allowlisted subset of the reviewer output blob (stamphog version, reviewer exit code). The raw reviewer stdout, PR payload, changed-file patches, and policy file contents are excluded. The reviewer's reasoning, the text stamphog posts on GitHub, is in `reasoning` instead. */
readonly output: _ReviewOutputSummary;
+ /** The reviewer's reasoning, the same text stamphog posts as its GitHub review. Returned only when retrieving a single run, and null in list results. Its fields are null until the reviewer has run. */
+ readonly reasoning: _ReviewReasoning | null;
/** Error message if the run failed, blank otherwise. */
readonly error: string;
/**
@@ -85399,6 +85430,29 @@ export namespace Schemas {
has_more: boolean;
}
+ /**
+ * Request body for asking stamphog to review one pull request.
+ */
+ export interface ReviewRequest {
+ /** Full name of the GitHub repository, e.g. 'PostHog/posthog'. It must be connected and enabled in Stamphog. */
+ repository: string;
+ /**
+ * Pull request number on GitHub.
+ * @minimum 1
+ */
+ pr_number: number;
+ }
+
+ /**
+ * The review run a request points at.
+ */
+ export interface ReviewRequestResponse {
+ /** The review run for the pull request's current head. Poll it by id until status is terminal (completed, gated, failed, or superseded). */
+ readonly run: ReviewRun;
+ /** True when this request queued a new run. False when a queued, running, or finished run already covered the current head, which is returned instead. */
+ readonly created: boolean;
+ }
+
export interface ReviewResolutionConfig {
/** Name of the `review-hog-resolution-*` skill this row represents (the criteria's identity). */
skill_name: string;
@@ -112090,7 +112144,7 @@ export namespace Schemas {
*/
status?: string;
/**
- * Filter by what caused the run: self_driving, label, or all.
+ * Filter by what caused the run: self_driving, manual, label, or all.
*/
trigger?: StamphogReviewRunsListTrigger;
};
@@ -112101,6 +112155,7 @@ export namespace Schemas {
export const StamphogReviewRunsListTrigger = {
All: 'all',
Label: 'label',
+ Manual: 'manual',
SelfDriving: 'self_driving',
} as const;
diff --git a/services/mcp/src/generated/stamphog/api.ts b/services/mcp/src/generated/stamphog/api.ts
index 01212fd1455a..8ee75a6d64ff 100644
--- a/services/mcp/src/generated/stamphog/api.ts
+++ b/services/mcp/src/generated/stamphog/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 8 enabled ops
+ * PostHog API - MCP 9 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -102,7 +102,7 @@ export const StamphogRepoConfigsDestroyParams = () => zod.object({
})
/**
- * Read-only history of stamphog review runs, filterable by repository, PR number, and status.
+ * History of stamphog review runs, filterable by repository, PR number, and status, plus manual review requests.
*/
export const StamphogReviewRunsListParams = () => zod.object({
project_id: zod
@@ -119,13 +119,35 @@ export const StamphogReviewRunsListQueryParams = () => zod.object({
repository: zod.string().optional().describe("Filter by repository full name, e.g. 'PostHog\/posthog'."),
status: zod.string().optional().describe('Filter by review run status.'),
trigger: zod
- .enum(['all', 'label', 'self_driving'])
+ .enum(['all', 'label', 'manual', 'self_driving'])
.optional()
- .describe('Filter by what caused the run: self_driving, label, or all.'),
+ .describe('Filter by what caused the run: self_driving, manual, label, or all.'),
})
/**
- * Read-only history of stamphog review runs, filterable by repository, PR number, and status.
+ * History of stamphog review runs, filterable by repository, PR number, and status, plus manual review requests.
+ */
+export const StamphogReviewRunsCreateParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const StamphogReviewRunsCreateBody = () => zod
+ .object({
+ repository: zod
+ .string()
+ .describe(
+ "Full name of the GitHub repository, e.g. 'PostHog\/posthog'. It must be connected and enabled in Stamphog."
+ ),
+ pr_number: zod.number().min(1).describe('Pull request number on GitHub.'),
+ })
+ .describe('Request body for asking stamphog to review one pull request.')
+
+/**
+ * History of stamphog review runs, filterable by repository, PR number, and status, plus manual review requests.
*/
export const StamphogReviewRunsRetrieveParams = () => zod.object({
id: zod.string(),
diff --git a/services/mcp/src/tools/generated/stamphog.ts b/services/mcp/src/tools/generated/stamphog.ts
index 1897d12151cd..303c8acabca4 100644
--- a/services/mcp/src/tools/generated/stamphog.ts
+++ b/services/mcp/src/tools/generated/stamphog.ts
@@ -144,6 +144,35 @@ const stamphogRepoConfigsList = (): ToolBase<
},
})
+const StamphogReviewRunsCreateSchema = () => {
+ const StamphogReviewRunsCreateBody = orvalSchemas.StamphogReviewRunsCreateBody()
+ return StamphogReviewRunsCreateBody
+}
+
+const stamphogReviewRunsCreate = (): ToolBase<
+ ReturnType<typeof StamphogReviewRunsCreateSchema>,
+ Schemas.ReviewRequestResponse
+> => ({
+ name: 'stamphog-review-runs-create',
+ schema: StamphogReviewRunsCreateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof StamphogReviewRunsCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.repository !== undefined) {
+ body['repository'] = params.repository
+ }
+ if (params.pr_number !== undefined) {
+ body['pr_number'] = params.pr_number
+ }
+ const result = await context.api.request<Schemas.ReviewRequestResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/stamphog/review_runs/`,
+ body,
+ })
+ return result
+ },
+})
+
const StamphogReviewRunsGetSchema = () => {
const StamphogReviewRunsRetrieveParams = orvalSchemas.StamphogReviewRunsRetrieveParams()
return StamphogReviewRunsRetrieveParams.omit({ project_id: true })
@@ -189,7 +218,7 @@ const stamphogReviewRunsList = (): ToolBase<
})
const filtered = {
...result,
- results: (result.results ?? []).map((item: any) => omitResponseFields(item, ['output'])),
+ results: (result.results ?? []).map((item: any) => omitResponseFields(item, ['output', 'reasoning'])),
} as typeof result
return await withPostHogUrl(context, filtered, '/stamphog')
},
@@ -202,6 +231,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'stamphog-repo-configs-delete': stamphogRepoConfigsDelete,
'stamphog-repo-configs-get': stamphogRepoConfigsGet,
'stamphog-repo-configs-list': stamphogRepoConfigsList,
+ 'stamphog-review-runs-create': stamphogReviewRunsCreate,
'stamphog-review-runs-get': stamphogReviewRunsGet,
'stamphog-review-runs-list': stamphogReviewRunsList,
}